A hook to handle asynchronous tasks.
callback
(function
): The asynchronous function to execute.dependencies
(array
, optional): Dependency array to control when the async function should be executed.
- An object containing
data
,error
, andloading
.
import useAsync from './useAsync';
export default function AsyncComponent() {
const { loading, error, value } = useAsync(
async () => {
const res = await fetch('/api/data');
return res.json();
},
[
/* dependencies */
],
);
return (
<div>
<div>Loading: {loading}</div>
<div>{error}</div>
<div>{value}</div>
</div>
);
}