All hooks / Timers
useDebouncedValue
Returns value, but only after it has stopped changing for delayMs. Starts as value (also on the server), then lags behind while it changes.
With Chinese, Japanese, or Korean input, the text changes in steps while a character is composed. Keep the input's own state updating, and debounce a separate query that you set only when e.nativeEvent.isComposing is false and in onCompositionEnd.
Import
import { useDebouncedValue } from '@vincent.ri/react-tils'
// or only this hook
import { useDebouncedValue } from '@vincent.ri/react-tils/useDebouncedValue'Usage
const [query, setQuery] = useState('')
const debouncedQuery = useDebouncedValue(query, 300)
const results = useSearch(debouncedQuery) // your data-fetching hook
return <input value={query} onChange={(e) => setQuery(e.target.value)} />Live demo
The debounced copy catches up after you pause.
When to use it
Deriving a request from fast-changing state, e.g. fetching search results for a query typed into a controlled input.
When not to
You have an event handler to debounce instead of a value; use useDebouncedCallback, which also has cancel and flush. To keep typing responsive while rendering something expensive, use React's useDeferredValue, which has no fixed delay.
API
function useDebouncedValue<T>(value: T, delayMs: number): T| Parameter | Description |
|---|---|
value | The value to debounce. Compared with Object.is: pass a primitive or a memoized object. A new array or object every render re-renders every delayMs forever. |
delayMs | How long value must stay unchanged. |
Browser support
Uses only long-established browser features, so it works wherever React does.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).
Coming from another library?
Other libraries call this useDebounce, useDebounceValue.