Home > database >  useEffect clean up being called on mounting
useEffect clean up being called on mounting

Time:09-04

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

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

}

CodePudding user response:

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

  • Related