@r01al/use-debounced-state
v0.1.0
Published
A small, type-safe React hook that debounces state updates.
Maintainers
Readme
useDebouncedState
useDebouncedState is a small, type-safe React hook that keeps state updates
immediate while also exposing a value that updates after a quiet period.
Installation
npm install @r01al/use-debounced-stateReact 18 or newer is required as a peer dependency.
Usage
import { useDebouncedState } from '@r01al/use-debounced-state';
function Search() {
const [query, setQuery, debouncedQuery] = useDebouncedState('', 300);
return (
<>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<p>Debounced query: {debouncedQuery}</p>
</>
);
}query updates immediately, so the controlled input stays responsive.
debouncedQuery updates 300 milliseconds after the latest call to setQuery.
All three values are typed as string from the inferred initial value.
API
function useDebouncedState<Value>(
initialValue: Value | (() => Value),
delay?: number,
): readonly [
value: Value,
setValue: (newValue: Value) => void,
debouncedValue: Value,
];initialValueis available immediately and can be a lazy initializer.delayis measured in milliseconds and defaults to300.valueupdates immediately whenever the setter is called.debouncedValueupdates after the delay. Calling the setter again restarts its timer, so only the latest value is committed to it.- A pending timeout is cleared automatically when the component unmounts.
Unlike React's normal state setter, this hook's setter accepts a value rather than a functional updater. Function values themselves are supported when the generic type is provided explicitly.
License
MIT
