React useState extra render unexpected – JavaScript – SitePoint Forums

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 (
        

You clicked {count} times

); } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

I intentionally set the setCount handler to just the const value for experimental reasons. And there is something very strange for me – the app renders the second time when I click the button the second time! (I am in the process of Example exit on the first and ALSO on the second click!)

My BIG question is HOW can this happen if in the case of the second click the value of the count the variable has NOT changed since the first click! ? (first time clicking is set to just 1 and the second time ALSO for 1!)

When I click the third and more times, it seems to work as expected – there are no more other renders…

Can someone explain to me the reason for this extra rendering after the second click?

PS

PLEASE don’t tell me the cause of this may be the react strict mode – As everyone can CLEARLY see, I do NOT use the strict mode everywhere!!!


It’s strange isn’t it?

If you change button on Click to

You would then expect to see ‘Example’ registered twice, but it is only registered once.

There is a similar question on stackoverflow, but for me this does not answer the question satisfactorily.

Maybe someone here can clarify? I’ll have to dig a little on this one.

Just to try and see a pattern, I try the following.

const { useState } = React;

let index = 0;
const sequence = [0,0,1,1,1,0,0,0]

export const App = () => {
  const [count, setCount] = useState(0);

  console.log('rendered')

  return (
    

You clicked {count} times

); }

Production

rendered
index 0 - value is 0
index 1 - value is 0
index 2 - value is 1
rendered
index 3 - value is 1
rendered // (not committed to DOM)
index 4 - value is 1
index 5 - value is 0
rendered
index 6 - value is 0
rendered // (not committed to DOM)
index 7 - value is 0
index 8 - value is 0
index 9 - value is 0
...

James S. Joseph