DEV Community

Nic
Nic

Posted on

Updating a state hook object

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

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

setState(state.proficiency: 'lost');
Enter fullscreen mode Exit fullscreen mode

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

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.

Top comments (0)