One of the common problem faced by many new React learners is with count++ in useState hook. It is common practice to use ‘++’ operator in JavaScript to increment a variable. But, if we try to use the same with React useState, it do not work (or it behaves strangely like one time it increments and another time it do not).

If we see the official documentation, clearly it is ‘count+1’ inside useState and not count++. So if you change from count++ to count+1, then the application will run normally.

So what is the difference between ‘count++’ and ‘count+1’ in useState.

In JavaScript, count++ is equivalent to ‘count=count+1’.

In React, we should not modify the state variables directly. We need to pass the new data to the state variable modifier functions (such as setCount), then React will modify the value of the state variable.

One more thing we need to remember is, when we do count++ in JavaScript, the variable will be incremented after consuming the variable first.

So, when we do setState(count++), first the value of count will be passed to the setState function, then the value of count will be incremented inside the function component (this is not recommended way).

What is the problem with count++ with useState hook ?

Suppose, if we start the application with the count value 0, first when we click on the button, we pass the value 0 to the setState then increment the count. Since the value passed to the setState is same as of initial run (0), React do not update the DOM.

When you click on the button second time, then you pass the previously incremented value of count (1) to setState, then increment the count to 2. Since you passed 1 to setState, it will update the state but resets the count value back to 1. Now, when you click on third time, you pass this value (1) to setState and increment the counter. This time, since the value didn’t change, React do not update the DOM.

This is the reason why the counter gets incremented only when you click twice on the button.

Instead of count++, you can use ++count (when you ++count, first the variable will be incremented then it will be consumed in JavaScript).

Though the application runs normally without any problem with ++count, it is also equivalent to modifying the state variable directly, so not recommended. The better practice is to pass the new value to the state modifier function. So, when we pass count + 1, we are passing a value to the setState and not modifying the count by ourselves.