DEV Community

Uriel Bitton
Uriel Bitton

Posted on

6 5

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay