Toggle state in an object REACT HOOKS

What is the best practice to toggle a boolean in a state object for react?

I understand for just a boolen in general

setState(current => !current)

but I am a bit lost when it comes to a complex obj like so (I want to toggle scheduled without mutating the state)

const [bio, setBio] = useState({
name: 'John',
age: 27,
scheduled: false

Am I supposed to still use a callback? How would the callback look and how do I ensure that I update the desired key of the state obj the “right” way?

setBio(current => bio.!current.scheduled)

Yes, using setBio callback is required. It will need to set the whole object though, but with the wanted value changed.

For example:

const [data, setData] = useState({
  score: 0,
  checked: false

/* (...) */
  checked: !data.checked
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.