JAVASCRIPT

React useDebounce Hook for Input Search and Performance Optimization

Implement a custom `useDebounce` React hook to delay state updates, perfect for optimizing search inputs, preventing excessive API calls, and improving performance.

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 } from 'react';
import useDebounce from './useDebounce'; // Assuming useDebounce is in its own file

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

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log("Fetching data 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`. It maintains a `debouncedValue` state, which is updated only after the `value` has not changed for the specified `delay` period. A `useEffect` hook sets a `setTimeout` to update `debouncedValue`. If the `value` changes again before the timeout completes, the previous timeout is cleared, and a new one is set. This ensures the `setDebouncedValue` action only occurs once the user has stopped typing for the duration of the `delay`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs