How to resolve the useEffect runs twice issue
React 18, released in March 2022, brought about a change in the default behavior of the useEffect()
hook. It’s possible that you may not have noticed this change, as it was mentioned among numerous other new features in the React 18 launch post.
If you’ve recently updated your application to React 18 and are experiencing unexpected behavior, it may be because the useEffect
hook now runs twice by default. However, it’s important to note that this behavior occurs only in development mode and within the confines of strict mode, which is now the default setting for applications built with Vite, create-react-app, or Next.js.
There are valid reasons for this change, and it’s not necessarily a problem with your code. It’s simply how things now work in React.
To revert back to the previous behavior and disable the double execution of useEffect
, you have to disable strict mode. This serves as a temporary workaround until you can address any issues introduced by this change.
In Vite, you can remove the <React.StrictMode>
wrapper component from the src/main.jsx
file:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
);
For Next.js, you can add the following option to your next.config.js
file:
module.exports = {
reactStrictMode: false
}
In create-react-app, you can remove the StrictMode higher-order component from your index.js
file:
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
<App />
);
By following these steps, you can restore the previous behavior of useEffect
and mitigate any issues caused by the double execution.
Tags: React, useEffect, strict mode