Rohit Sharma
Rohit Sharma

Reputation: 169

No strict mode - Why does my React component render three times when I click a button multiple times?

I have a simple React component that uses a state hook. The initial state is false, and when a button is clicked, the state is set to true. I have a console.log statement in the component to log when it renders.

Here is my code:

import { useState } from 'react';

function App() {
  const [value, setValue] = useState(false);

  function changeState() {
    setValue(true);
  }

  return (
    <>
      {console.log('rendered!')}
      <button onClick={changeState}>Click</button>
    </>
  );
}

export default App;

When I click the button multiple times, I see the message "rendered!" logged three times in the console. I expected it to be logged twice - once for the initial render, and once for the re-render after the state change. Can anyone explain why it's being logged an extra time?

Upvotes: 0

Views: 48

Answers (1)

Ben
Ben

Reputation: 101

I tried your code in React 18 and I do not have this problem.

In older version, more re-renders can be expected. This shouldn't be an issue as the reconciliation process is pretty swift

https://legacy.reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update

What version of React are you using?

Upvotes: 0

Related Questions