JAVASCRIPT

Create a useDebounce Custom Hook for Input Values

Implement a custom `useDebounce` hook to delay updating a value until a certain time has passed, ideal for search inputs or expensive calculations.

import React, { useState, useEffect } => 'react';

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

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

    // Cleanup function to clear the timeout if value or delay changes
    // or if the component unmounts.
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]); // Only re-call effect if value or delay changes

  return debouncedValue;
}

function SearchInput() {
  const [inputValue, setInputValue] = useState('');
  const debouncedSearchTerm = useDebounce(inputValue, 500);

  // Effect for API call or expensive operation
  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Performing search for:', debouncedSearchTerm);
      // In a real application, you would make an API call here
    }
  }, [debouncedSearchTerm]);

  return (
    <div>
      <input
        type="text"
        placeholder="Type to search (debounced)"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <p>Original Value: {inputValue}</p>
      <p>Debounced Value: {debouncedSearchTerm || '...'}</p>
    </div>
  );
}

export default SearchInput;
How it works: This snippet presents a `useDebounce` custom hook. It takes a `value` and a `delay` as arguments. Internally, it uses `useState` to maintain a `debouncedValue` and `useEffect` to set a timeout. The `debouncedValue` is only updated after the specified `delay` has passed since the `value` last changed. The cleanup function clears the timeout, ensuring that the previous timer is cancelled if the value changes before the delay is met. This pattern is extremely useful for optimizing performance by limiting the rate at which expensive operations (like API calls on search input) are executed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs