I have a functional component react version is 17
export default function Comp(props){
.
.
.
useEffect(() => {
return () => {// cleanup
console.log("Called!")
}
}, [...dependiences])
}
I have another button that mounts and unmounts the component
for some reason, the clean-up function is getting called on mounting the component
and I can see the console Log
How can I prevent this from happening and call the clean up only if the component is un-mounting
The parent creates the component like this
export default function Comp(props){
.
.
.
const [mount, setMount] = useState(false);
return <> {mount && <Child {...someProps}/>}</>
}
If you're using
React 18and your app is wrapped in the<StrictMode>tag, then this is expected behavior added on purpose in the hopes to help devs catch bugs relevant to the lifecycle of their components, such as abusing/misusing theuseEffecthook.What the new
StrictModeactually does is unmount and then remount every component once it gets rendered.Resulting in an initial lifecycle that looks like this:
Note that it only behaves this way in dev environment, and not in the production build.
ref: https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors