06/11/2025
⚡ Day 37 of my React.js Journey
Today’s topic: Building a Custom Hook — useDebounce
When a user types fast (like in a search bar), we don’t want to call the API on every keystroke.
👉 We “debounce” the input — wait for the user to stop typing before running the logic.
Let’s build it! 👇
import { useState, useEffect } from "react";
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
// Usage
function Search() {
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 600);
useEffect(() => {
if (debouncedQuery) console.log("Search for:", debouncedQuery);
}, [debouncedQuery]);
return setQuery(e.target.value)} placeholder="Search..." />;
}
âś… Why useDebounce matters:
Prevents unnecessary API calls
Boosts performance
Creates a smoother user experience
đź’ˇ Used in search bars, live filters, or form validations!
Tomorrow: Building a Custom Hook — usePrevious (track previous values) 🔄