Explore / Human feedback Generate a React custom hook for asynchronous functions Save Share Download ▾ ReportPrivate research annotation Sign in to add a private research label or note.
Generate a React custom hook for asynchronous functions
Here's a custom React hook for handling asynchronous functions. This hook, useAsync, takes a function as an argument and returns the current status (loading, error, or success), as well as a run function to execute the provided async function.
I prefer to use a reducer for the state
Here's an updated version of the useAsync hook that uses the useReducer hook to manage the state. This approach allows for better separation of concerns and easier state updates.
Don't we need dependancies?
Yes, you're correct. I apologize for the oversight. The useCallback hook should include the dispatch function in its dependency array to ensure that the execute function is updated when the dispatch function changes.
Here's the corrected version of the useAsync hook:
Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Model Unknown
Provider unknown
Model provenance As recorded by source dataset
Turns 3 (6 messages)
Language Not recorded
Added to archive Nov 22, 2026
ID 01m80txtfbh7k7djwbkdej64reSource & license Imported from NVIDIA HelpSteer3 Preference (source ). Imported records earn no Research Points.
Upstream record: preference/train.jsonl.gz:3454:response2
nvidia/HelpSteer3, revision f6d145777bcbde96137596340fab89793acd1031. Original NVIDIA preference release. Each response becomes a separate transcript retaining its shared context. Generator identity is not supplied per row. Dialogue normalized; system instructions, tools and private metadata omitted.
License: CC-BY-4.0
Cite this conversation “Generate a React custom hook for asynchronous functions.” Conversation with an AI model, from the NVIDIA HelpSteer3 Preference dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80txtfbh7k7djwbkdej64re
Copy citation
import { useState, useCallback, useEffect } from 'react';
export function useAsync(asyncFunction, immediate = true) {
const [status, setStatus] = useState('idle');
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
const execute = useCallback(
(...args) => {
setStatus('pending');
setValue(null);
setError(null);
return asyncFunction(...args)
.then(response => {
setValue(response);
setStatus('success');
})
.catch(error => {
setError(error);
setStatus('error');
});
},
[asyncFunction]
);
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, status, value, error };
}
Here's how you can use this useAsync hook in a functional component:
javascript Copy code
import React from 'react';
import { useAsync } from './useAsync';
function fetchUser(id) {
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(response =>
response.json()
);
}
function User({ userId }) {
const { status, value: user, error } = useAsync(() => fetchUser(userId), true);
if (status === 'loading') return <div>Loading...</div>;
if (status === 'error') return <div>Error: {error.message}</div>;
if (status === 'idle' || status === 'success') return <div>{user.name}</div>;
}
function App() {
return <User userId={1} />;
}
export default App;
import { useReducer, useCallback, useEffect } from 'react';
const ACTIONS = {
IDLE: 'idle',
PENDING: 'pending',
SUCCESS: 'success',
ERROR: 'error',
};
const initialState = {
status: ACTIONS.IDLE,
value: null,
error: null,
};
function reducer(state, action) {
switch (action.type) {
case ACTIONS.PENDING:
return { status: ACTIONS.PENDING, value: null, error: null };
case ACTIONS.SUCCESS:
return { status: ACTIONS.SUCCESS, value: action.payload, error: null };
case ACTIONS.ERROR:
return { status: ACTIONS.ERROR, value: null, error: action.payload };
default:
return state;
}
}
export function useAsync(asyncFunction, immediate = true) {
const [state, dispatch] = useReducer(reducer, initialState);
const execute = useCallback(
(...args) => {
dispatch({ type: ACTIONS.PENDING });
return asyncFunction(...args)
.then(response => {
dispatch({ type: ACTIONS.SUCCESS, payload: response });
})
.catch(error => {
dispatch({ type: ACTIONS.ERROR, payload: error });
});
},
[asyncFunction]
);
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, ...state };
}
The usage of the hook remains the same as in the previous example. The main difference is that now the state is managed using a reducer, which makes it easier to handle complex state updates in the future if needed.
import { useReducer, useCallback, useEffect } from 'react';
const ACTIONS = {
IDLE: 'idle',
PENDING: 'pending',
SUCCESS: 'success',
ERROR: 'error',
};
const initialState = {
status: ACTIONS.IDLE,
value: null,
error: null,
};
function reducer(state, action) {
switch (action.type) {
case ACTIONS.PENDING:
return { status: ACTIONS.PENDING, value: null, error: null };
case ACTIONS.SUCCESS:
return { status: ACTIONS.SUCCESS, value: action.payload, error: null };
case ACTIONS.ERROR:
return { status: ACTIONS.ERROR, value: null, error: action.payload };
default:
return state;
}
}
export function useAsync(asyncFunction, immediate = true) {
const [state, dispatch] = useReducer(reducer, initialState);
const execute = useCallback(
(...args) => {
dispatch({ type: ACTIONS.PENDING });
return asyncFunction(...args)
.then(response => {
dispatch({ type: ACTIONS.SUCCESS, payload: response });
})
.catch(error => {
dispatch({ type: ACTIONS.ERROR, payload: error });
});
},
[asyncFunction, dispatch] // Include dispatch in the dependency array
);
useEffect(() => {
if (immediate) {
execute();
}
}, [execute, immediate]);
return { execute, ...state };
}
Now, the execute function will be updated whenever the asyncFunction or dispatch changes, ensuring that the latest version of the dispatch function is used when executing the async function.
Dataset releases Not yet included in a published release.