Why does useEffect run two times?

How to fix the useEffect runs twice problem

⭐️ 👀 2023 WEB DEVELOPMENT BOOTCAMP starting in days! Join the waiting list to reserve your spot in my 10-weeks cohort course and learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much much more! 👀 ⭐️

React 18 released in March 2022 changed the default behavior of useEffect().

I didn’t even realize it at first, reading the React 18 launch post, buried along a lot of new features.

If your application is behaving strangely after updating to React 18, the default behavior of useEffect changed to run it 2 times.

Just in development mode, but this is the mode everyone builds their application on.

And just in strict mode, but that’s now the default for applications built using create-react-app or Next.js.

There are reasons for this.

It’s not a problem of your code - it’s how things work now in React.

The only way to disable this behavior is to disable strict mode.

Strict mode is important so this is a temporary workaround until you can fix any issue this change introduced.

You can do it in Next.js by adding the option

reactStrictMode: false

in your next.config.js file.

In create-react-app you can go in your index.js file and remove the StrictMode higher order component, from:

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

to

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 />
);

One more thing! ⚠️ ✋

At the end of January I will organize the Web Development Bootcamp.

It's a 10-weeks long cohort online course where I will guide you to becoming a Web Developer.

It's not "just a course". It's a big event I organize once a year.

We'll start from zero, learn the fundamentals of Web Development, HTML CSS, JavaScript, Tailwind, Git, using the command line, VS Code, GitHub, Node.js, we'll then learn React, JSX, how to use PostgreSQL, Astro, Next.js, Prisma, deploying on Netlify/DigitalOcean/Fly/Vercel and much more! 

At the end of the first 10 weeks you'll know how to create web sites and web applications and I'll unlock you the 2nd phase of the Bootcamp: you will get access to a large number of projects exclusive to the Bootcamp graduates, so you can follow my instructions to build things like private areas with authentication, clones of popular sites like Twitter YouTube Reddit, create e-commerce sites, and much much more.

Because once you got the fundamentals, you only learn by working on real, exciting projects.

To find out more, visit bootcamp.dev