Blog>
Snippets

Debouncing a Search Input using debounce Effect

Use the `debounce` effect to implement a search input that triggers an API call, debouncing subsequent calls to limit the number of requests.
import { useState, useEffect } from 'react';
import { debounce } from 'lodash';
This code snippet imports the necessary hooks from React and the debounce function from lodash.
const useDebouncedSearch = (searchFunction) => {
  const [inputValue, setInputValue] = useState('');
  
  useEffect(() => {
    const debouncedSearch = debounce(searchFunction, 300);
    if (inputValue) debouncedSearch(inputValue);
    
    // Cleanup function to cancel the debounced call on component unmount
    return () => debouncedSearch.cancel();
  }, [inputValue, searchFunction]);
  
  return { inputValue, setInputValue };
};
This custom hook, `useDebouncedSearch`, accepts a search function as a parameter. It uses the `useState` hook to keep track of the search input's value. The `useEffect` hook sets up a debounced version of the passed search function, which is called whenever the input value changes. A cleanup function is also provided to cancel any pending debounced calls when the component unmounts or the input changes.
const MySearchComponent = () => {
  const { inputValue, setInputValue } = useDebouncedSearch((value) => {
    console.log('Search for:', value); // Replace with actual search function call
  });
  
  return (
    <input
      type="text"
      value={inputValue}
      onChange={(e) => setInputValue(e.target.value)}
      placeholder="Search..."
    />
  );
};
This component, `MySearchComponent`, uses the `useDebouncedSearch` hook we defined earlier. It provides an input field where users can type their search query. As the user types, `setInputValue` updates `inputValue`, triggering the useEffect in our custom hook, which in turn debounces the search function calls, reducing the frequency of API requests.