@sanity/ui 3.1.13 → 3.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/ui",
3
- "version": "3.1.13",
3
+ "version": "3.1.14",
4
4
  "keywords": [
5
5
  "sanity",
6
6
  "ui",
@@ -47,6 +47,26 @@ describe('useDelayedState', () => {
47
47
  expect(result.current[0]).toBe(true)
48
48
  })
49
49
 
50
+ it('should clear pending timeout on unmount', () => {
51
+ jest.useFakeTimers()
52
+ const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout')
53
+ const {result, unmount} = renderHook(() => useDelayedState(false))
54
+ const [, setState] = result.current
55
+
56
+ act(() => {
57
+ setState(true, 1000)
58
+ })
59
+
60
+ clearTimeoutSpy.mockClear()
61
+
62
+ // Unmount while the delayed update is still pending
63
+ unmount()
64
+
65
+ // clearTimeout should have been called during cleanup
66
+ expect(clearTimeoutSpy).toHaveBeenCalledTimes(1)
67
+ clearTimeoutSpy.mockRestore()
68
+ })
69
+
50
70
  it('should cancel update if the set state was called with a new state', () => {
51
71
  const {result} = renderHook(() => useDelayedState(false))
52
72
  const [, setState] = result.current
@@ -1,4 +1,4 @@
1
- import {SetStateAction, useCallback, useRef, useState} from 'react'
1
+ import {SetStateAction, useCallback, useEffect, useRef, useState} from 'react'
2
2
 
3
3
  /**
4
4
  * @beta
@@ -24,5 +24,13 @@ export function useDelayedState<S>(
24
24
  delayedAction.current = setTimeout(action, delay)
25
25
  }, [])
26
26
 
27
+ useEffect(() => {
28
+ return () => {
29
+ if (delayedAction.current) {
30
+ clearTimeout(delayedAction.current)
31
+ }
32
+ }
33
+ }, [])
34
+
27
35
  return [state, onStateChange]
28
36
  }