Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre increment operator in React?

Tags:

reactjs

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?

like image 780
Neha Gour Avatar asked Dec 02 '25 23:12

Neha Gour


1 Answers

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" :)

like image 63
Chris Avatar answered Dec 04 '25 14:12

Chris