react-use-debouncer
v1.2.1
Published
Debounced state hook for ReactJS
Downloads
7
Maintainers
Readme
react-use-debouncer
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
Features
- Debounced state
- Cancelable debounced callback function
Docs
useDebouncedState
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]
useDebouncedCallback
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]
Usage
useDebouncedState
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
useDebouncedCallback
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>;
};
Future
- Leading & trailing options
- Better CodeSandBox examples
- Better docs