React hook to debounce any value
Quick Answer
useDebounce returns a delayed copy of a value that only updates after the user has stopped changing it for the specified number of milliseconds. It is the React-idiomatic way to avoid firing API calls on every keystroke.
1import { useState, useEffect } from 'react';
2
3function useDebounce<T>(value: T, delay: number): T {
4 const [debouncedValue, setDebouncedValue] = useState<T>(value);
5
6 useEffect(() => {
7 const handler = setTimeout(() => {
8 setDebouncedValue(value);
9 }, delay);
10
11 return () => {
12 clearTimeout(handler);
13 };
14 }, [value, delay]);
15
16 return debouncedValue;
17}useDebounce delays propagating a value change until a specified period of inactivity. This is the React-idiomatic way to debounce — rather than debouncing functions directly, you debounce the value and react to the debounced version in useEffect or wherever you need it.
Debouncing the value with useDebounce is more composable in React because you can react to the debounced value anywhere — in useEffect, useMemo, or a query hook.
300 ms is the standard. It feels responsive to fast typists but avoids firing on every individual keystroke.
Yes. The useEffect cleanup function calls clearTimeout when the component unmounts, preventing state updates on unmounted components.
This free typescript code snippet for usedebounce hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement usedebounce hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.