debounce-for-react
Version:
A simple and lightweight React hook for debouncing values. Ideal for optimizing performance in search fields, input handling, and other scenarios where you want to limit the rate of updates.
25 lines (20 loc) • 563 B
JavaScript
import { useState, useEffect } from "react";
/**
* A hook that debounces a value.
*
* @param value - The value to debounce.
* @param delay - The debounce delay in milliseconds.
* @returns The debounced value.
*/
export function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}