19
Hooks

useDebounce

A hook that delays the updating of a value until a specified time has passed since the last update.

useDebounce

The useDebounce hook delays the updating of a value until a specified time has passed since the last update. This is useful for reducing the frequency of updates in scenarios like:

  • Search inputs to avoid making API calls on every keystroke
  • Form inputs that trigger expensive calculations
  • Window resize events that should only trigger updates after the user has finished resizing
Raw Value:
Debounced Value:

Installation

Install the useDebounce hook using:

npx axionjs-ui add hook use-debounce

File Structure

use-debounce.ts

Parameters

PropTypeDefault
value
T (generic type)
Required
delay
number
500

Return Value

PropTypeDefault
debouncedValue
T (same type as the input value)
-

Examples

Search with Debounce

A common use case for debouncing is with search inputs, where you want to avoid making API calls on every keystroke.

Start typing to search

Enter a search term

Resize Event Debouncing

Window resize events can fire rapidly during resizing, so debouncing helps optimize performance.

import { useState, useEffect } from "react";
import { useDebounce } from "@/hooks/use-debounce";
 
function WindowSizeTracker() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
 
  // Debounce window size to avoid excessive re-renders
  const debouncedWindowSize = useDebounce(windowSize, 200);
 
  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };
 
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
 
  return (
    <div>
      <p>Debounced Width: {debouncedWindowSize.width}px</p>
      <p>Debounced Height: {debouncedWindowSize.height}px</p>
    </div>
  );
}

Use Cases

  • Search Inputs: Reduce API calls while typing
  • Form Validation: Delay validation until the user stops typing
  • Auto-Save: Wait until the user finishes typing before saving
  • Resize Handlers: Optimize performance during window resizing
  • Scroll Events: Process scroll events less frequently for performance
  • Filter/Sort Operations: Delay expensive data operations until user input is stable

Accessibility

This hook doesn’t directly impact accessibility, but proper use can improve user experience by reducing UI jank and ensuring responsive interfaces.

Best Practices

  • Choose an appropriate delay based on the use case (typically 300-500ms for typing)
  • Use debouncing for expensive operations that don’t need to run on every input change
  • Consider providing visual feedback when debouncing causes a noticeable delay
  • For immediate UI updates with debounced processing, maintain both the raw and debounced values

On this page