A React hook to run effect only if a component is mounted.
- Credits to Lukas Klinzing for his article about potential memory leak when using
React.useEffectasynchronously - Credits to Étienne Martin for the repository template
To add use-mounted-effect to your project, run:
yarn add use-mounted-effector
npm install use-mounted-effectWhen 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.
You can use useMountedEffect like you would use React.useEffect, but it provides you the following benefits:
- You can pass an
asynccallback - Your effect will be called with an
isMounted()argument that it can use to check if the component is still mounted
const [data, setData] = React.useState();
useMountedEffect(async (isMounted) => {
const { data } = await fetch(url);
if (!isMounted()) return;
setState(data);
}, []);