Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do components in react only renders twice when I change the state from the button click

I have been learning react recently, and I created a component in which I have created three buttons: "post", "user", and "comment". When I click one of the buttons, the name of the button shows below the buttons and also logs the button's name, which is console. I am confused as to why a button logs the name only twice in console if clicked consecutively, since from my understanding it should log only once. I tried removing <React.StrictMode> from the index.js file but still it only logs twice. Example: if the user button is clicked twice consecutively, it logs its name twice but not more if clicked again, it should log into the console only once. I think it is related to the useState hook. Please help me understand this react behaviour. Here is my code:

export default function Hello() {

const [resourceType, setResourceType] = useState('post')

console.log(resourceType)

return (
  <div>
      <button onClick={() => setResourceType('post')}>Post</button>
      <button onClick={() => setResourceType('user')}>User</button>
      <button onClick={() => setResourceType('comment')}>Comments</button>
      <h1>{resourceType}</h1>
  </div>
  )
}
like image 341
Prashant Singh Avatar asked Nov 18 '25 17:11

Prashant Singh


1 Answers

The value is logged twice on two consecutive clicks of the same button, and then not on subsequent consecutive clicks, because of the State hook's bailout. As @Armands alluded to in his comment, the answer is in the React docs (API Hooks Reference) referenced in this post which states:

Bailing out of a state update
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects.

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

So if your case, since the console.log(...) is in the component body, it's still being fired before React "bails out".

like image 140
Steve Gomez Avatar answered Nov 21 '25 07:11

Steve Gomez