2

This is one of the most basic things in React but I wonder why counter+1 is working, but in counter++ you must double click to increase the number?

import React, { useState } from "react";
import "./App.css";

function App() {
  const [counter, setCounter] = useState(0);
  const counterHandler = () => {
    setCounter(counter + 1);
  };
  return (
    <div className="App">
      {counter}
      <button onClick={counterHandler}>Increment</button>
    </div>
  );
}

export default App;
muller
  • 41
  • 8
  • 1
    `++counter` would have worked. `counter++` is equivalent with returning old counter value, and then incrementing the variable. Clicking twice would be buggy. – Joop Eggen Dec 02 '21 at 08:35
  • @callmenikk why? state is not mutable by nature , I'm just changing it by setCounter , what I can I do Instead ? – muller Dec 02 '21 at 08:50
  • 1
    oh my bad, I had to say never use `let` or `var` on useState() – callmenikk Dec 02 '21 at 08:51

2 Answers2

2
let x = 3
let y = x++
//output: x=4 y=3

let x = 3
let y = ++x
//output: x=4 y=4

It's why you need to double click because you have next logic:

console.log(counter) //0
//triggers click
console.log(counter) //0, useState re-assigned to 0
//triggers click 
console.log(counter) //1, useState re-assigned to 1
illia chill
  • 1,652
  • 7
  • 11
2

Difference is that counter + 1 is only an operation and counter++ is an operation with an assignment. In React you shouldn't assign your state directly but use the setter method. So in your case it is better to use counter + 1

Vitali
  • 176
  • 1
  • 3