1.0.5 • Published 2 years ago

use-mounted-effect v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

use-mounted-effect

npm bundle size npm

A React hook to run effect only if a component is mounted.

Installation

To add use-mounted-effect to your project, run:

yarn add use-mounted-effect

or

npm install use-mounted-effect

Purpose

When using an asynchronous effect, it can be a potential memory leak.

const [state, setState] = React.useState();

React.useEffect(() => {
  setInterval(() => setState(...), 10_000);
}, []);

If the component is unmounted before the setTimer callback is fired, the state will be updated on something that isn't existing anymore.

This hook will run your effect only if the component is mounted.

Usage

You can use useMountedEffect like you would use React.useEffect, but it provides you the following benefits:

  • You can pass an async callback
  • Your effect will be called with an isMounted() argument that it can use to check if the component is still mounted

Example

const [data, setData] = React.useState();

useMountedEffect(async (isMounted) => {
  const { data } = await fetch(url);

  if (!isMounted()) return;

  setState(data);
}, []);
1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago