When dealing with real-time user input, like search fields, triggering actions on every keystroke can cause performance issues. Debouncing helps by delaying execution until the user stops typing.
π Let's Build a Simple Debounce Function:
import React, { useState, useEffect } from 'react'; function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } const SearchBar = () => { const [query, setQuery] = useState(''); const handleSearch = (q) => { console.log('Searching for:', q); // Perform search action here }; const debouncedSearch = debounce(handleSearch, 500); useEffect(() => { if (query) { debouncedSearch(query); } }, [query]); return ( <input type="text" placeholder="Search..." value={query} onChange={(e) => setQuery(e.target.value)} /> ); };
β‘ How it Works:
- The debounce function accepts a fn (function) and a delay (in milliseconds).
- It clears any existing timers and sets a new one to trigger the function after the specified delay.
- In this example, debouncedSearch triggers only after the user stops typing for 500 milliseconds.
π‘ Why it Matters:
Itβs a lightweight solution that improves performance, especially in apps with real-time inputs like search fields.
Happy coding! π₯
Top comments (0)