I want to set state of variable as setoffsetCount(++offsetCount) or setoffsetCount(--ofsetCount) but I am not able to use this rather setoffsetCount(ofsetCount+1) setofsetCount(offsetCount-1)
is working fine.
How to use pre increment operator in React for setting the state?
The correct way is to do:
setofsetCount(ofsetCount+1)
because you are setting the new value to be the current one, plus one.
However, if you do:
setofsetCount(++ofsetCount)
you are mutating the state directly by first incrementing it by one and then setting the state with the updated value.
TL:DR
Continue doing setofsetCount(ofsetCount+1) because that's the correct way. The other approach you tried is anti-pattern.
Note, you have a spelling error. It's "offset", not "ofset" :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With