Home

React 18 - Avoiding Use Effect Getting Called Twice

Sunday, October 15th, 2023

0 views

React 18 introduced a huge breaking change, when in Strict Mode, all components mount and unmount, then mount again. The reason for this is for paving the way for a feature that isn't in React yet, so as far as React 18 is concerned, there is no reason.

For React Hooks in React 18, this means a useEffect() with zero dependencies will be executed twice.

Here is a custom hook that can be used instead of useEffect(), with zero dependencies, that will give the old (pre React 18) behaviour back, i.e. it works around the breaking change.

Here is the custom hook useEffectOnce without TypeScript:

And here is the hook again with TypeScript:

In your application code, call useEffectOnce with zero dependencies instead of useEffect. Job Done.

How it works in a nutshell, I observed in React 18, if the effect runs, and then gets destroyed again before it renders, we know it's a fake setup / destroy cycle. This works regardless of what React version, and regardless of whether Strict Mode is used or not.