← Back to all snippets
JAVASCRIPT

Debounce State Changes with `useDebounce`

Create a custom React hook, `useDebounce`, to delay updating a state value, optimizing performance for fast-changing inputs like search fields and resize events.

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 SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500); // Debounce for 500ms

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Searching for:', debouncedSearchTerm);
      // Perform API call or heavy computation here
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: The `useDebounce` hook takes a `value` and a `delay` as arguments. It maintains an internal `debouncedValue` state. Whenever the `value` changes, a `setTimeout` is set to update `debouncedValue` after the specified `delay`. If the `value` changes again before the timeout expires, the previous timeout is cleared, and a new one is set. This ensures that the `debouncedValue` only updates after a period of inactivity, which is perfect for optimizing expensive operations like API calls triggered by user input.

Need help integrating this into your project?

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

Hire DigitalCodeLabs