Making a simple counter-example. What am I doing wrong here?
import React from "react";
import { useState } from "react";
export default function Ex2() {
const [counter, setCounter ] = useState(0);
const increaseValue = () => {
setCounter(counter++);
}
const decreaseValue = () => {
setCounter(counter--);
}
return (
<div className="ex2">
<p>{counter}</p>
<p><button onClick={increaseValue}>increase</button><button onClick={decreaseValue}>Decrease</button></p>
</div>
)
}
Error:
3
Answers
setCounter(counter++);
andsetCounter(counter--);
are actually changing the variable at the end of the line as well, not giving youcounter + 1
andcounter - 1
, but it’s a constant, so that error is throwncounter++
is an operation that is the logical equivalent ofcounter = counter + 1
. It’s attempting to modify the state value directly, which is prohibited in React.counter + 1
is an expression without assignment, so it’s evaluated as a new value when passed to yourset
function.That’s the real problem with your code. However, the actual compilation error is because by incrementing the state value you’re attempting to reassign a constant.
In your code you are doing
counter++
which is trying to increase the counter with post increment operator++
variable.Remember to always use setter function to update your state.
There are a few ways you can update your counter by doing :
setCounter(counter+1)
or use below callback approach
Below is the better approach using setState callback.