JAVASCRIPT

Implementing a useDebounce Custom Hook in React

Create a custom `useDebounce` React hook to delay function execution, optimizing performance for real-time input fields like search bars and 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;
}

// How to use:
/*
import React, { useState } from 'react';
import useDebounce from './useDebounce'; // Assuming useDebounce.js

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

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log("Searching for:", debouncedSearchTerm);
      // Perform actual search API call here
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: The `useDebounce` hook delays updating a value until a specified `delay` has passed since the last change. This is crucial for optimizing performance in scenarios like search inputs, preventing expensive operations (e.g., API calls) from firing on every keystroke, and only executing them once the user pauses typing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs