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 18 and 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 the useEffect hook.
What the new StrictMode actually does is unmount and then remount every component once it gets rendered.
Resulting in an initial lifecycle that looks like this:
* React mounts the component.
  * Layout effects are created.
  * Effects are created.
* React simulates unmounting the component.
  * Layout effects are destroyed.
  * Effects are destroyed.
* React simulates mounting the component with the previous state.
  * Layout effects are created.
  * Effects are created.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With