-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathuseDebouncedState.ts
32 lines (30 loc) · 1.04 KB
/
useDebouncedState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useState, Dispatch, SetStateAction } from 'react'
import useDebouncedCallback, {
UseDebouncedCallbackOptions,
} from './useDebouncedCallback.js'
/**
* Similar to `useState`, except the setter function is debounced by
* the specified delay. Unlike `useState`, the returned setter is not "pure" having
* the side effect of scheduling an update in a timeout, which makes it unsafe to call
* inside of the component render phase.
*
* ```ts
* const [value, setValue] = useDebouncedState('test', 500)
*
* setValue('test2')
* ```
*
* @param initialState initial state value
* @param delayOrOptions The milliseconds delay before a new value is set, or options object
*/
export default function useDebouncedState<T>(
initialState: T | (() => T),
delayOrOptions: number | UseDebouncedCallbackOptions,
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState(initialState)
const debouncedSetState = useDebouncedCallback<Dispatch<SetStateAction<T>>>(
setState,
delayOrOptions,
)
return [state, debouncedSetState]
}