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 (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:
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:
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
?
✅ Prevents excessive API calls.
✅ Improves performance in search-heavy applications.
✅ Enhances user experience by reducing flickering results.
✅ Can be reused across multiple components.
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.
Top comments (0)