DEV Community

Mulligan81
Mulligan81

Posted on

React useState unexpected extra render

Taking this simple React counter example:

`const { useState } = React;

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  console.log("Example")

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(1)}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);`
Enter fullscreen mode Exit fullscreen mode

I've intentionally set the setCount handler to just const value for experimental reasons. And there is something very strange to me - the App re-renders the second time when I click the button the second time! (I'm getting Example output on the first and ALSO on the second click!)

My BIG question is HOW can it happen if in the case of the second click the value of the count variable HASN'T changed since the first click!? (by clicking the first time is set to just 1 and the second time ALSO to 1!)

When I click the third time and more it seems to work as expected - there are no further re-renders...

Can someone please explain me the reason of this extra render after the second click?

P.S.

PLEASE don't tell me that the cause of this may be the react strict mode - As anyone can CLEARLY see I'm NOT using the strict mode anywhere!!!

Discussion (1)

Collapse
aeryle profile image
Aeryle

The way I see it right now, when your component gets mounted it will log Example and it will also log it when updating the state. Your component gets mounted once and your state is updated once. Makes it log twice.