0

I clicked the button div, and the console printed

click
111
setState
111
setState

why the setState always execute twice This is my code

function App() {
  const [num, setNum] = useState(0);
  console.log('111');
  return (
    <div>
      {num}
      <div onClick={ () => {
        console.log('click');
        setNum( num => {
          console.log('setState');
          return num + 1;
        })
      }}>button</div>
    </div>
  )
}
tttinkl
  • 19
  • 1
  • Does this answer your question? [Why is my function being called twice in React?](https://stackoverflow.com/questions/50819162/why-is-my-function-being-called-twice-in-react) – keikai Apr 02 '20 at 07:11

2 Answers2

0

in index.js remove this <React.StrictMode> </ React.StrictMode> and u will see it rendering only once.

Mohiuddin
  • 80
  • 5
-1

But does num after click equals to 2 or 1 ?

Maybe this form will work better?

function App() {
  const [num, setNum] = useState(0);
  console.log('111');
  return (
    <div>
      {num}
      <div onClick={ () => {
        console.log('click');
        setNum(num + 1)
      }}>button</div>
    </div>
  )
}

Also maybe try to use button for clicking, instead of div?

Tonoslav
  • 517
  • 2
  • 6
  • 20