Closed
Description
React version: 18.0.x, 18.1.x, 18.2.x
Steps To Reproduce
- Visit provided sandbox
- Open console and observe logs displayed twice.
- 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>
);
}