useDebouncedAsyncEffect
Starts only the latest asynchronous effect after a debounce window.
About
useDebouncedAsyncEffect combines dependency-driven effects, debouncing, and a current-generation guard. It is useful for searches and autosaves where rapid dependency changes should collapse into one asynchronous start.
Examples
import { useState } from "react";
import { useDebouncedAsyncEffect } from "rooks";
export default function DebouncedLookup() {
const [query, setQuery] = useState("");
const [result, setResult] = useState("Type a value");
useDebouncedAsyncEffect(
async (shouldContinueEffect) => {
const next = await Promise.resolve(query.toUpperCase());
if (shouldContinueEffect()) setResult(next || "Type a value");
},
[query],
300
);
return (
<label>
Value
<input value={query} onChange={(event) => setQuery(event.target.value)} />
<span role="status">{result}</span>
</label>
);
}Parameters
| Argument | Type | Default | Meaning |
|---|---|---|---|
effect | (shouldContinueEffect: () => boolean) => Promise<T> | required | Work to start after the debounce window. |
deps | DependencyList | required | Changes cancel the pending call and schedule another. |
delay | number | 500 | Debounce delay in milliseconds. |
cleanup | (result: T | void) => void | undefined | Runs for the ending dependency generation. |
options | { leading?: boolean; trailing?: boolean; maxWait?: number } | undefined | Lodash-style debounce controls. |
Return value
The hook returns void.
Behavior and lifecycle
A dependency change invalidates running work, cancels a pending debounced call, invokes that generation's cleanup, and schedules the latest effect. Cleanup receives a stored result only when the still-current invocation resolved before cleanup. shouldContinueEffect() does not abort work; pair it with AbortController when cancellation matters.
The latest effect is used, while delay and options are captured when the hook first creates its debounced function. Remount to apply changed debounce configuration. A rejection from the current invocation is rethrown from the async callback, so catch expected failures inside effect; rejections from invalidated invocations are suppressed.
Compatibility and accessibility
Effects do not run during server rendering. Any browser API used by effect still needs feature detection. Announce delayed results or errors when they materially change what a user can do.