DEV Community

Discussion on: React 18 - Avoiding Use Effect Getting Called Twice

Collapse
 
joelnet profile image
JavaScript Joel

Probably just a minor copy/paste bug, but there is an extra open parenthesis here that doesn't have a matching close below.

export const useEffectOnce = ( effect => {
Enter fullscreen mode Exit fullscreen mode

I am also seeing a problem when Strict mode is not enabled or app is build in production mode, the unmount event will not fire.

Here's my code for testing:

export const MyComponent = () => {
  useEffect(() => {
    console.log("useEffect enter");

    return () => {
      console.log("useEffect exit");
    };
  }, []);

  useEffectOnce(() => {
    console.log("useEffectOnce enter");

    return () => {
      console.log("useEffectOnce exit");
    };
  });

  return <b>Hi</b>;
};
Enter fullscreen mode Exit fullscreen mode

Output in production mode when mounting and unmounting the component once.

useEffect enter
useEffectOnce enter
useEffect exit
Enter fullscreen mode Exit fullscreen mode

useEffectOnce exit was expected to fire here.

Collapse
 
jherr profile image
Jack Herrington

useEffectOnce exit is not going to fire as far as I can see. This hook works to defeat the hook being called twice, but the cleanup functions will never get called as far as I can see.

I honestly don't know how to fix this. I've been trying everything I can think of.

Collapse
 
eviltester profile image
Alan Richardson

Thanks for pointing this out Jack. Niall updated the code, hopefully it is better.

Collapse
 
eviltester profile image
Alan Richardson

Thanks, we've updated the code to fix typos and hopefully addressed Jack's point below.

Collapse
 
mike7petrusenko profile image
Mike

What is the difference between development and production hook behavior? Could you please explain.

Collapse
 
skydiver profile image
Martin M.