Skip to main content

Function: useSequentialRequest()

useSequentialRequest<T>(requestFn): () => Promise<T>

Defined in: use-sequential-request.ts:118

A custom React hook for managing sequential asynchronous requests with automatic cancellation.

This hook ensures that only the most recent request is processed by automatically canceling any previous ongoing requests when a new request is initiated. This is particularly useful for handling rapid user interactions (like search inputs or button clicks) where only the latest request's result matters.

When a new request is triggered while another is in progress, the previous request is immediately aborted using the AbortSignal API. This prevents race conditions and ensures that stale data doesn't override newer results.

The hook also handles cleanup on component unmount, automatically canceling any pending requests to prevent memory leaks and unwanted state updates.

Type Parameters​

T​

T

The type of data expected from the request.

Parameters​

requestFn​

(signal) => Promise<T>

The asynchronous request function that should accept an AbortSignal parameter for cancellation support. This function should handle the abort signal appropriately (e.g., pass it to fetch API).

Returns​

A callback function that triggers the request. When called, it cancels any previous ongoing request and starts a new one. The returned promise resolves with the request result or rejects with "CanceledError" if canceled.

() => Promise<T>

Examples​

const searchUsers = useSequentialRequest(async (signal) => {
const response = await fetch(`/api/users?query=${query}`, { signal });
return response.json();
});

// In an event handler:
const handleSearch = async () => {
try {
const results = await searchUsers();
setResults(results);
} catch (error) {
if (error.message !== "CanceledError") {
console.error("Search failed:", error);
}
}
};
const submitForm = useSequentialRequest(async (signal) => {
const response = await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(formData),
signal
});
return response.json();
});

// Only the last submission will complete
await submitForm();

For a live, editable example, see the useSequentialRequest docs page.