useDebouncedEffect
Delays an effect until its dependencies stop changing.
About
useDebouncedEffect schedules a React effect through a debounced callback. Rapid dependency changes cancel the pending call, making the hook useful for delayed validation, filtering, and other synchronous effects.
Examples
import { useState } from "react";
import { useDebouncedEffect } from "rooks";
export default function DebouncedPreview() {
const [draft, setDraft] = useState("");
const [preview, setPreview] = useState("");
useDebouncedEffect(() => setPreview(draft), [draft], 300);
return (
<label>
Draft
<input value={draft} onChange={(event) => setDraft(event.target.value)} />
<span>Preview: {preview}</span>
</label>
);
}Parameters
| Argument | Type | Default | Meaning |
|---|---|---|---|
effect | EffectCallback | required | Runs after the debounce window and may return cleanup. |
deps | DependencyList | required | React-style dependencies that schedule the effect. |
delay | number | 500 | Debounce delay in milliseconds. |
options | { leading?: boolean; trailing?: boolean; maxWait?: number } | undefined | Lodash-style debounce controls. |
Return value
The hook returns void.
Behavior and lifecycle
Before a dependency generation ends, the hook cancels its pending call and runs the cleanup returned by the last completed effect. If the next effect eventually runs, it replaces that cleanup. Unmounting performs the same cancellation and cleanup.
The latest effect function is used, but delay and options are captured on the first render because the underlying debounced function remains stable. Remount to apply changed debounce configuration. Synchronous exceptions propagate when the debounced effect executes. React Strict Mode can replay effect setup and cleanup in development.
Compatibility and accessibility
The timer works without a DOM, and effects are skipped during server rendering. Delayed validation or status changes should remain understandable to keyboard and assistive-technology users; use a live region for important asynchronous feedback.