2

When I use useState several times with the same value as the previous value, the component is executed once and then nothing.

From what I understand so far, when the state is updated with the same value, nothing should happen.

import { useState } from 'react'

function App() {
  const [count, setCount] = useState(0)

  console.log('RENDER')

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  )
}

export default App

If I press the + button several times (let's say 3 times), the state changes and the component is executed 3 times. The RENDER message is also displayed in the console each time.

If now I press the reset button several times. I have the message RENDER which is displayed twice then nothing.

The first time because the state changes, 3 to 0. The second time, the state is the same. So why is RENDER displayed again in the console?

1 Answer 1

2

This should give you some idea

https://legacy.reactjs.org/docs/hooks-reference.html#functional-updates

If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.

This essentially means that when your setState(0) gets called the first time, it returns 0 but the current state is 3 which the virtual DOM evaluates it as a requirement to update the real DOM causing the re-render to occur. This also tells the virtual DOM to cause subsequent re-renders too.

The second time you call setState(0) the current state is 0 and the value to set is also 0 which means there should not be any subsequent re-renders based on the value 0 but a re-render should be performed to update the virtual and real DOM to have a "locked" state of 0. Again, subsequent re-renders based on the value 0 won't be triggered.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.