useEffect for async functions. The effect gets a mounted() function that
tells it when its result is stale, and can resolve to a cleanup function.
Works in React DOM and React Native, and ships ESM, CommonJS and TypeScript
types.
npm install --save @atomic-reactor/use-async-effectreact (16.8+) is a peer dependency. The package has no other dependencies.
import { useState } from 'react';
import { useAsyncEffect } from '@atomic-reactor/use-async-effect';
export function TaskList({ projectId }: { projectId: string }) {
const [tasks, setTasks] = useState<Task[]>([]);
useAsyncEffect(
async (mounted) => {
const result = await fetchTasks(projectId);
if (mounted()) setTasks(result);
},
[projectId],
);
return <ul>{tasks.map(/* ... */)}</ul>;
}| Argument | Description |
|---|---|
cb |
async (mounted) => void | cleanup. Runs after render, like a useEffect callback |
deps |
Reruns cb when these change. Works like useEffect's deps: omitted means every render, [] means mount only |
mounted() returns true until the component unmounts or deps change.
Check it after each await before setting state, so a slow response can't
overwrite a newer one.
If cb resolves to a function, it's called when the component unmounts or
deps change:
useAsyncEffect(async () => {
const socket = await connect(roomId);
return () => socket.close();
}, [roomId]);An async function can't hand back its cleanup synchronously, so the cleanup
runs once cb has finished. If the component unmounts while cb is still
waiting, the cleanup is called as soon as cb resolves.
The hook uses only React and ES2019 built-ins and is compiled to ES2019, so it needs no polyfills in any current browser, React Native 0.60+ or Node 12+.
MIT