DEV Community

Uriel Bitton
Uriel Bitton

Posted on

React Tricks Miniseries 7: How to setState for different data types

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
Enter fullscreen mode Exit fullscreen mode

Object states are set by using the spread syntax:

Objects

setUser(prev => {
  ...user,
  newKey: newValue,
  //OR
  updateKey: updateValue
})
Enter fullscreen mode Exit fullscreen mode

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}]) 
Enter fullscreen mode Exit fullscreen mode

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)