JAVASCRIPT

Efficiently Debounce a Value in React with useDebounce Hook

Learn how to create a custom `useDebounce` React hook to delay updates of any value, perfect for optimizing search inputs or costly computations by preventing excessive re-renders.

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:
/*
import React, { useState, useEffect } from 'react';

function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay

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

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: This `useDebounce` hook takes a value and a delay, returning a debounced version of that value. It uses `useEffect` to set a timeout that updates the internal `debouncedValue` state only after the specified `delay` has passed without the original `value` changing. This is highly useful for scenarios like search inputs, where you want to wait for the user to finish typing before triggering an expensive operation (e.g., an API call), preventing unnecessary executions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs