A simple debounced state hook that I use on some of my projects.
Install with npm:
npm i --save react-use-debouncer
or via yarn:
yarn i react-use-debouncer
- Debounced state
- Cancelable debounced callback function
const [state, setState] = useDebouncedState(initialValue, delay);
- initialValue: The initial value that state is initialized with
- delay(optional): Number indicating the milliseconds to wait before setting state
Returns an array containing the debounced state and a setState function.
ex: [state, setState]
const [debouncedCallback, cancelCallback] = useDebouncedCallback(callback, delay);
- callback: Callback function to be debounced
- delay(optional): Number indicating the milliseconds to wait before calling the function
Returns an array containing the debounced callback function and a cancel function
ex: [debouncedCallback, cancelCallback]
import { useDebouncedState } from 'react-use-debouncer';
const useStateExample = () => {
const [state, setState] = useDebouncedState('Initial');
return (
<div className="App">
<span>{state}</span>
<input onChange={({ target: { value } }) => setState(value)} />
</div>
);
};
Or check it out on CodeSandbox
import { useDebouncedCallback } from 'react-use-debouncer';
const sampleFunction = () => console.log('There should be a delay before I appear!');
const useCallbackExample = () => {
const [debouncedCallback, cancelCallback] = useDebouncedCallback(sampleFunction);
return <button onClick={() => debouncedCallback()}>Click Me!</button>;
};
- Leading & trailing options
- Better CodeSandBox examples
- Better docs