I'm Fairly new to React and JS, just exploring the nitty-gritties of the lang.
I'm trying to compare the difference in updating the state variable "counter", using the ++ operator( and by idiomatic way of counter + 1).
The error I get for the following snippet is:
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = () => {
setCounter(++counter);
};
console.log(counter);
return (
<>
<button onClick={incrementCounter}>Increase </button>
</>
App.jsx?t=1714542208954:31 Uncaught TypeError: Assignment to constant variable.
at incrementCounter (App.jsx?t=1714542208954:31:18)
at HTMLUnknownElement.callCallback2 (react-dom_client.js?v=38cf15c3:3672:22)
at Object.invokeGuardedCallbackDev (react-dom_client.js?v=38cf15c3:3697:24)
at invokeGuardedCallback (react-dom_client.js?v=38cf15c3:3731:39)
at invokeGuardedCallbackAndCatchFirstError (react-dom_client.js?v=38cf15c3:3734:33)
at executeDispatch (react-dom_client.js?v=38cf15c3:7014:11)
at processDispatchQueueItemsInOrder (react-dom_client.js?v=38cf15c3:7034:15)
at processDispatchQueue (react-dom_client.js?v=38cf15c3:7043:13)
at dispatchEventsForPlugins (react-dom_client.js?v=38cf15c3:7051:11)
at react-dom_client.js?v=38cf15c3:7175:20
Note: I get the error after I click on Increase button
When I try to call the setState function( setCounter ) using counter + 1
the error disappears, I cant wrap my head around the cause.
I get that pre/post fix operators are not suitable for updating react state by I wonder why is the case.
Any insights would be greatly appreciated.
This is basic Javascript, the counter
state is declared const
so it can not be reassigned.
const [counter, setCounter] = useState(0); // <-- const
const incrementCounter = () => {
setCounter(++counter); // <-- ++counter is a reassignment
};
Consider the following code:
const foo = 0;
foo++; // error, can't be reassigned!
counter++
is basically synonymous to counter = counter + 1
, which fails since counter
can't be reassigned. Pre/Post-incrementing adds one to the current value and assigns the value back to the variable.
If you need to increment a count state in React the idiomatic method is to use a functional state update and add one to the previous state value.
const [counter, setCounter] = useState(0);
const incrementCounter = () => {
setCounter(counter => counter + 1);
};
Using setCounter(counter + 1)
works similarly in that you are not reassigning or mutating the counter
state, but simply updating the counter
state to the result of adding 1
to its value.