useState Hook in ReactJS

49 Views Asked by At

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.

1

There are 1 best solutions below

0
Flavio Del Grosso On

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