Skip to content

Bug: useEffect runs twice on component mount (StrictMode, NODE_ENV=development) #24502

Closed
@cytrowski

Description

@cytrowski

React version: 18.0.x, 18.1.x, 18.2.x

Steps To Reproduce

  1. Visit provided sandbox
  2. Open console and observe logs displayed twice.
  3. Click the button and observe the rendering log happens twice, the effect log happens once.

Link to code example: https://codesandbox.io/s/react-18-use-effect-bug-iqn1fx

The current behavior

The useEffect callback runs twice for initial render, probably because the component renders twice. After state change the component renders twice but the effect runs once.

The expected behavior

I should not see different number of renders in dev and prod modes.

Extras

The code to reproduce:

import { useEffect, useReducer } from "react";
import "./styles.css";

export default function App() {
  const [enabled, toggle] = useReducer((x) => !x, false);

  useEffect(() => {
    console.log(
      "You will see this log twice for dev mode, once after state change - double effect call"
    );
  }, [enabled]);

  console.log("You will see this log twice for dev mode - double rendering");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={() => toggle()}>
        Toggle me: {enabled ? "on" : "off"}
      </button>
    </div>
  );
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions