use-mount-effect
v1.0.0
Published
A React hook triggered only once on mount.
Downloads
7
Maintainers
Readme
useMountEffect
A React hook triggered only once on mount.
Background
Why does my effect run twice when the component mounts?? It's f**king annoying!
Well. That is not a bug in React, actually it's by design according to the doc:
When Strict Mode is on, in development, React runs setup and cleanup one extra time before the actual setup.
There are some workarounds to solve this problem, but people still feel it's a hassle. That's why I made this.
Install
npm install --save use-mount-effect
Usage
Basic usage:
import { useMountEffect } from "use-mount-effect";
const MyComponent = () => {
useMountEffect(() => {
// Do something only when the component mounts.
});
return <div>Blah blah blah</div>;
};
With cleanup:
import { useMountEffect } from "use-mount-effect";
const MyComponent = () => {
useMountEffect(() => {
// Do something only when the component mounts.
return () => {
// Do something only when the component unmounts.
};
});
return <div>Blah blah blah</div>;
};
Notes
You should really fix your effects if you find your app works incorrectly due to the strict mode, because it implies some logic errors or resource leakage.
Always use this hook with caution.
License
MIT