0

When this react website renders for the first time on browser, it prints "hi" twice in the console. But according to my knowledge, it should print "hi" once in the console.

My project structure is website Structure

inside App.js

import { useState } from "react";

export default function Counter() {

  const [number, setNumber] = useState(0);
  console.log("hi");
  return (
    <>
      <h1>{number}</h1>
      <button
        onClick={() => {
          setNumber(number + 1);
          setNumber(number + 1);
          setNumber(number + 1);
        }}
      >
        +3
      </button>
    </>
  );
}

inside index.js

import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";

import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

If you notice issues related to the code, then you can see my public repo on codesandbox: website repo

I was expecting the right answer of the above code in the console.

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

3

The double rendering behavior in development mode is related to the React.StrictMode wrapper.

See https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-double-rendering-in-development

Flavio Del Grosso
  • 490
  • 2
  • 7
  • 21