-
Notifications
You must be signed in to change notification settings - Fork 0
useAsync
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
Manage complex asynchronous data fetching with a clean state object. This hook handles loading states, error catching, data storage, and prevents stale responses automatically.
The simplest possible implementation, executing immediately.
import { useAsync } from 'react-hook-lab';
function BasicUser() {
const { data, loading, error } = useAsync(() => fetch('/api/user').then(res => res.json()));
if (loading) return <div>Loading...</div>;
if (error) return <div>Error!</div>;
return <div>{data?.name}</div>;
}The most frequent real-world implementation, using dependencies to refetch when an ID changes.
import { useAsync } from 'react-hook-lab';
function UserProfile({ userId }) {
const { data, loading, error, retry } = useAsync(
() => fetch(`/api/users/${userId}`).then(res => res.json()),
[userId]
);
if (loading) return <div>Loading spinner...</div>;
if (error) return <div>Error: {error.message} <button onClick={retry}>Retry</button></div>;
return <div>Welcome, {data?.name}</div>;
}An exhaustive example utilizing every possible configuration option, including deferred execution and initial data.
import { useAsync } from 'react-hook-lab';
function AdvancedDashboard({ query }) {
const { data, loading, error, execute, reset } = useAsync(
async () => {
const response = await fetch(`/api/search?q=${query}`);
if (!response.ok) throw new Error('Search failed');
return response.json();
},
[query],
{
immediate: false, // Wait for manual execution
initialData: { results: [] } // Provide initial fallback data
}
);
return (
<div>
<button onClick={execute} disabled={loading}>Run Search</button>
<button onClick={reset}>Reset</button>
{loading && <p>Searching...</p>}
{error && <p>Error: {error.message}</p>}
<ul>
{data.results.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
</div>
);
}-
asyncFunction(Required)- Type:
() => Promise<T> - Description: The asynchronous function to execute. It must return a Promise.
- Type:
-
dependencies- Type:
any[] - Default:
[] - Description: Standard React dependency array. When these values change, the
asyncFunctionis re-evaluated and automatically executed (unlessimmediate: false).
- Type:
-
options- Type:
UseAsyncOptions<T> - Default:
{} - Description: Configuration object.
-
immediate: (boolean, default:true) If true, theasyncFunctionexecutes immediately on mount and when dependencies change. If false, it waits forexecute()to be called. -
initialData: (T, default:undefined) The initial value ofdatabefore the first execution completes.
-
- Type:
Returns UseAsyncReturn<T>:
-
data(T | undefined): The resolved data from the promise, orinitialData. -
error(Error | null): The caught error if the promise rejects. -
loading(boolean): True while the promise is in-flight. -
execute(() => Promise<T | undefined>): Function to manually trigger the async operation. -
retry(() => Promise<T | undefined>): Function to re-execute the async operation (identical toexecute). -
reset(() => void): Function to clear errors, stop loading, and revertdataback toinitialData.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM