0

I've recently jumped into studying react and encountered this trouble. Why can't I use increment operators when changing the state?

function App() {
  const [num, setNum] = useState(0);

  const changeNum = () => {
    setNum(num + 1)
  } 
  return (
    <div>
      <i className='xi-heart' onClick={changeNum}></i> {num}
    </div>
  );
}

I want to count the number of clicks. When I use increment operator num++ instead of num + 1, it's not working. have been researching for the answer and found some (How to use the increment operator in React) but still don't understand. You should never mutate the state. Okay. Then How does num++ mutate the state directly but num+1 does not?

Seung
  • 1
  • num++ returns the same value. See this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description – kiranvj Jul 28 '22 at 03:37
  • 1
    You technically could use `num++` if you declared the variable with `let` instead of `const`, and then passed the result to `setNum` - but it'd be easier to use preincrement instead - or, even better, make things less confusing and simply pass the number plus one, instead of also incrementing the state variable (which is really weird, although not entirely forbidden) – CertainPerformance Jul 28 '22 at 03:37

0 Answers0