UNPKG

865 BJavaScriptView Raw
1import { useState } from 'react';
2import useDebouncedCallback from './useDebouncedCallback';
3
4/**
5 * Similar to `useState`, except the setter function is debounced by
6 * the specified delay. Unlike `useState`, the returned setter is not "pure" having
7 * the side effect of scheduling an update in a timeout, which makes it unsafe to call
8 * inside of the component render phase.
9 *
10 * ```ts
11 * const [value, setValue] = useDebouncedState('test', 500)
12 *
13 * setValue('test2')
14 * ```
15 *
16 * @param initialState initial state value
17 * @param delayOrOptions The milliseconds delay before a new value is set, or options object
18 */
19export default function useDebouncedState(initialState, delayOrOptions) {
20 const [state, setState] = useState(initialState);
21 const debouncedSetState = useDebouncedCallback(setState, delayOrOptions);
22 return [state, debouncedSetState];
23}
\No newline at end of file