Skip to content

About

useEffect for async functions: a React hook that tells your async effect when its result is stale, and runs the cleanup it resolves to. Works in React DOM and React Native.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@atomic-reactor/use-async-effect

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.

Install

npm install --save @atomic-reactor/use-async-effect

react (16.8+) is a peer dependency. The package has no other dependencies.

Usage

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>;
}

useAsyncEffect(cb, deps?)

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.

Cleanup

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.

Compatibility

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+.

License

MIT

About

useEffect for async functions: a React hook that tells your async effect when its result is stale, and runs the cleanup it resolves to. Works in React DOM and React Native.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages