Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect clean up being called on mounting

I have a functional component

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}/>}</>

}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading