Updating a state hook object

·

1 min read

You might want your state hook to be an object. Which is fine, it can absolutely be one.

  const [state, setState = useState({
    language: 'React',
    proficiency: 'confused'
  });

The trouble comes when you try to update it. You might think you can do this:

setState(state.proficiency: 'lost');

Seems logical, right? Except that as well as updating that one object, it's also wiped the other one. Thanks React.

The solution is to set it to itself when you update:

setState({ ...state proficiency: 'beginner'});

Here you're setting an object. The ...state bit destructures it. In other words, tells React 'here it all is'. And then after that, you can update the element you want to update. You don't need to put 'state' before it, because it already knows that from the destructuring.