Skip to content Skip to sidebar Skip to footer

Pre Or Post Incrementing React State With ++ Throws Read Only Error

import React, {useState} from 'react'; function App(){ const [counter, setCounter] = useState(0); const onIncrement = () => { setCounter(++counter) }; return(

Solution 1:

In ReactJS, the count variable is immutable, read-only, and when you use the ++ increment you are trying to directly change the count variable

when you use the setCounter () function by passing count + 1, you are passing a value, without changing the original value of the variable. Under the hood, setCounter makes a copy of the count with this updated value, maintaining immutability

Solution 2:

++ Operator tries to alter the variable itself, and at a theoretical level counter being readonly React state naturally should throw an error. Curiously enough this error is avoided by using a "let" initializer with your state; therefore the error is encountered by trying to alter the value of a constant. Although following functional operations (with no side effects) one should make the change in a more safely manner. One simple way to do this might be:

constonIncrement = () => {
    setCounter(counter+1);
}

Solution 3:

++counter

is equivalent to:

counter = counter + 1; 

so:

setCounter(++counter)

is roughly equivalent to:

setCounter(counter = counter + 1)

but since counter is const you get: Uncaught TypeError: "counter" is read-only

Post a Comment for "Pre Or Post Incrementing React State With ++ Throws Read Only Error"