0
0
ReactHow-ToBeginner · 4 min read

How to Create useDebounce Hook in React for Delayed Input Handling

Create a useDebounce hook in React by using useState and useEffect to delay updating a value until after a specified wait time. This helps reduce frequent updates, such as when typing in an input, by returning the debounced value only after the delay.
📐

Syntax

The useDebounce hook takes two parameters: the value to debounce and the delay in milliseconds. It returns the debounced value that updates only after the delay passes without changes.

Inside, it uses useState to store the debounced value and useEffect to set a timer that updates this value after the delay. The timer resets if the value changes before the delay ends.

javascript
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

This example shows a text input that updates a debounced value after 500 milliseconds of no typing. The debounced value is displayed below the input, updating only when typing pauses.

javascript
import React, { useState } from 'react';
import useDebounce from './useDebounce';

function SearchInput() {
  const [text, setText] = useState('');
  const debouncedText = useDebounce(text, 500);

  return (
    <div>
      <label htmlFor="search">Search:</label>
      <input
        id="search"
        type="text"
        value={text}
        onChange={e => setText(e.target.value)}
        aria-label="Search input"
      />
      <p>Debounced Value: {debouncedText}</p>
    </div>
  );
}

export default SearchInput;
Output
User types 'react' quickly; 'Debounced Value:' updates to 'react' only after 500ms pause.
⚠️

Common Pitfalls

  • Not clearing the timeout: Forgetting to clear the timer in useEffect cleanup causes multiple timers and unexpected updates.
  • Using stale values: Not including value or delay in the dependency array can cause the hook to use old values.
  • Too short delay: Setting delay too low defeats the purpose of debouncing.
javascript
function useDebounceWrong(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
  }, []); // Missing dependencies and no cleanup

  return debouncedValue;
}

// Correct way includes dependencies and cleanup:

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

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

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}
📊

Quick Reference

useDebounce Hook Cheat Sheet:

  • value: The input value to debounce.
  • delay: Time in milliseconds to wait before updating.
  • useEffect: Sets and clears the timer on value or delay change.
  • Returns the debounced value that updates only after delay.

Key Takeaways

useDebounce delays updating a value until after a specified wait time to reduce frequent changes.
Always clear the timeout in useEffect cleanup to avoid memory leaks and bugs.
Include all dependencies like value and delay in the useEffect dependency array.
Use useDebounce to improve performance in inputs or expensive calculations triggered by fast-changing values.