JAVASCRIPT

Creating a useDebounce Custom Hook for React Inputs

Optimize input handling in React with a `useDebounce` hook. Delay state updates until user input pauses, reducing unnecessary re-renders and API calls.

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

// Example Usage:
function SearchBar() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Fetching data for:', debouncedSearchTerm);
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
How it works: The `useDebounce` hook returns a debounced version of the input `value`. It uses `useEffect` to set a timeout that updates the internal `debouncedValue` state. If the `value` changes before the delay, the previous timeout is cleared, effectively resetting the debounce timer. This prevents actions from firing too frequently, e.g., on every keystroke.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs