Chaim Friedman
Chaim Friedman

Reputation: 6253

Why does useState cause the component to render twice on each update?

I have this simple bit of code here

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [number, setNumber] = useState(0);

  function chaneNumber() {
    setNumber(state => state + 1);
  }

  console.log("here");
  return (
    <div className="App">
      <button onClick={chaneNumber}>Change number</button>
      {number}
    </div>
  );
}

Every time I click the button, I get 2 logs in my console indicating that the component renders twice. I found one post saying this is about strict mode, but I have not enabled strict mode. Why is this component rendering twice on each state update?

Here is a codesandbox link to try it out.

Upvotes: 13

Views: 2200

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

Your App component is rendered within React.StrictMode which is what causes your code to run in strict mode and in strict mode the consoles are shown twice because each function is made to run twice in development mode

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);

According to react docs:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Upvotes: 23

Related Questions