React 18 useEffect behavior

React 18 useEffect behavior

If you have just made a new project using Create React App or updated to React version 18, you will notice that the useEffect hook is called twice in development mode. This is the case whether you used Create React App or upgraded to React version 18.

In this article, we'll learn about the useEffect hook in React 18's Strict Mode, which has a strange behavior.

The standard behavior of the useEffect hook was modified when React 18 was introduced in March of 2022.

If your application is acting weird after you updated to React 18, this is simply due to the fact that the original behavior of the useEffect hook was changed to execute the effect twice instead of once.

If we used the useEffect hook as follows:

useEffect(() => {
  console.log("First call on mount..");

  return () => console.log("Cleanup..");
}, []);

The output to the console should look like this:

First call on mount..
Cleanup..
First call on mount..

For future readers.

React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

The useEffect callback in this case runs twice for the initial render. After state change, the component renders twice, but the effect should run once.