This content originally appeared on DEV Community and was authored by Uriel Bitton
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.
This content originally appeared on DEV Community and was authored by Uriel Bitton
Uriel Bitton | Sciencx (2022-05-06T15:15:35+00:00) React Tricks Miniseries 7: How to setState for different data types. Retrieved from https://www.scien.cx/2022/05/06/react-tricks-miniseries-7-how-to-setstate-for-different-data-types/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.