Setting state in react has always been a tricky thing. There are many ways to do it, but most of them are anti-patterns, whereas only a few ways are correct and best practice.
Let's take a look at how to correctly set a react state in the scenarios of different data types.
Let's skip strings since those are trivial.
Numbers
Ignoring the case where we simply replace the number, updating a number state should be performed like this
setNumber(prev => prev + 1) //same for minus, multiple, divide, etc
Object states are set by using the spread syntax:
Objects
setUser(prev => {
...user,
newKey: newValue,
//OR
updateKey: updateValue
})
Array states are set by "creating" a new array inside the setState and simply inserting the new element after the previous state of the array.
Arrays
setFruits(prev => [...prev, 'apple'])
//or
setFruits(prev => [...prev, {name: 'Apple', price: 5}])
Conclusion
Setting states for different data types can get tricky, by using the best practices, always using the previous value, we can update the state using the proper methods.
Top comments (0)