React: Can I update the hook's state in the following way?

Hello,

I was wondering whether I can update the state’s hook value in the following way:

setCalcRow(calcRow.concat(displayNum.toString() + value))

I remember reading sometime ago that we cannot directly replace our state values in React, but at the same time .concat() method returns a new string as of it’s result.

Right now, my program seems to be working, visually at least, but would be a correct way to resolve my problem without violating React’s rules?

That doesn’t violate anything, you’re just setting a new value. However, it’s asynchronous, so you may see slightly wierd behaviour as you’re updating the state based on the current state. Use the function version to update:

setCalcRow((currentCalcRow) => currentCalcRow.concat(displayNum.toString() + value))
1 Like