S
Safal Bhandari
Guest
When working with search bars or live filtering in React, one common challenge is avoiding unnecessary API calls while the user is still typing. For example, if a user types "apple," you donβt want to send five API requests for each keystroke (
This is where debouncing comes into play. Debouncing ensures that a function only executes after a specified period of inactivity. In React, we can achieve this behavior using a custom hook.
The Custom
Letβs look at the code:
Hereβs how we can integrate
Why Use
Prevents excessive API calls.
Improves performance in search-heavy applications.
Enhances user experience by reducing flickering results.
Can be reused across multiple components.
The
Continue reading...
a
, ap
, app
, appl
, apple
). Instead, you want to wait until the user pauses typing and then trigger the search.This is where debouncing comes into play. Debouncing ensures that a function only executes after a specified period of inactivity. In React, we can achieve this behavior using a custom hook.
The Custom useDebounce
Hook
Letβs look at the code:
Code:
import React, { useEffect, useState } from "react";
const useDebounce = (inputValue, timeOut) => {
const [text, setText] = useState(undefined);
useEffect(() => {
const debounceTimeout = setTimeout(() => {
setText(inputValue);
}, timeOut);
return () => {
clearTimeout(debounceTimeout);
};
}, [inputValue, timeOut]);
return { text };
};
How it works:
- State (
text
) β Stores the debounced value. - Effect β Every time
inputValue
ortimeOut
changes, a new timeout is set. - Cleanup β If the user types again before the timeout finishes, the previous timeout is cleared.
- Final Behavior β Only after the user stops typing for the specified delay (
timeOut
), the value gets updated.
Using the Hook in a Search Bar
Hereβs how we can integrate
useDebounce
inside a search bar component:
Code:
const SearchBar = () => {
const [inputValue, setInputValue] = useState("");
const { text } = useDebounce(inputValue, 500); // 500ms debounce delay
console.log(text); // This updates only after user stops typing for 500ms
return (
<input
type='text'
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder='Search...'
/>
);
};
Example Flow:
- User types
hello
. - Keystrokes happen rapidly β debounce cancels previous timeouts.
- After 500ms pause, the hook sets
text = "hello"
. - This debounced value can now be used to call an API or filter a list.
Why Use useDebounce
?




Real-World Applications
- Search bars (Google-like instant search).
- Form validation with delay.
- Autosave functionality.
- Filtering large data sets.
Final Thoughts
The
useDebounce
hook is a must-have utility in React applications where user input triggers expensive operations like API calls. By introducing a slight delay, we make apps more efficient and user-friendly.Continue reading...