Snippets·Free
useDebounce hook (React)
useDebounce and useDebouncedCallback in TypeScript, plus a search box example. Both clear their timer when the component unmounts.
Free to install.
If PocketCode is installed on your Android device, this opens the page in the app.
Preview
useDebounce hookusedebounce
Hook that returns a value after it stops changing for a delay
import { useEffect, useState } from 'react';
/** Returns value once it has stopped changing for delayMs. */
export function useDebounce<T>(value: T, delayMs = ${1:300}): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delayMs);
// Runs on every change and on unmount, so no timer outlives the component.
return () => clearTimeout(timer);
}, [value, delayMs]);
return debounced;
}
$0useDebouncedCallback hookusedebouncedcb
Hook that delays a function until calls stop, for onChange or resize handlers
import { useCallback, useEffect, useRef } from 'react';
/** Returns a function that calls callback once calls stop for delayMs. */
export function useDebouncedCallback<A extends unknown[]>(
callback: (...args: A) => void,
delayMs = ${1:300},
) {
const callbackRef = useRef(callback);
const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
// Always call the latest callback without restarting the timer.
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Cancel a pending call when the component unmounts.
useEffect(() => () => clearTimeout(timerRef.current), []);
return useCallback(
(...args: A) => {
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => callbackRef.current(...args), delayMs);
},
[delayMs],
);
}
$0Debounced search querydebouncesearch
Search state that only reacts once the user stops typing (needs useDebounce)
const [${1:query}, set${2:Query}] = useState('');
const debouncedQuery = useDebounce(${1:query}, ${3:300});
useEffect(() => {
if (!debouncedQuery) return;
$0
}, [debouncedQuery]);Changes in 1.0.0
First version.