3
const App = () => {
   const [ counter, setCounter ] = useState(0)
   console.log(counter)

   return (
      <>
      <div>You clicked {counter} times.</div>
      <button onClick={ () => setCounter(counter+1) }>Click me!</button>
      </>
   )
}

Here's my react component. My question is when I run this, I see 0 two times in the console. Then when I click on the button, I see 1 two times in the console. Can anyone explain why does that happen? I was expecting 0, 1, 2 to be printed only once in the console whenever I click on the button.

Please forgive if this question has already been answered or my title of the question is not related with what I'm asking as this is my first question here.

Deep Parekh
  • 123
  • 1
  • 7

2 Answers2

1

It is because of React.StrictMode

If you go to your index.js , you will find that your App component is wrapped with <React.StrictMode>. If you strip off the StrictMode you will notice that your App component will render only once.

Refer the below doc to understand StrictMode

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer

Please refer: https://reactjs.org/docs/strict-mode.html

Praveen Dass
  • 586
  • 1
  • 3
  • 13
-1
return (<React.StrictMode><App /><React.StrictMode>)

This would solve your problem.

Kevin Li
  • 130
  • 5