Mastodon hachyterm.io

I’m now writing my React apps with Hooks.

I’m accustomed to the way setState() worked: state updates may be asynchronous and updates were merged.

That’s why I used functions instead of objects when calling setState(). Doing so ensured that you always get the newest values.

Example:

this.state = {
  person: {
    firstName: "",
    secondName: ""
  }
};

this.setState(prevState => ({
  person: {
    ...prevState.person,
    firstName: "Tom",
    secondName: "Jerry"
  }
}));

The useState Hook works differently.

During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.
React guarantees that setState function identity is stable and won’t change on re-renders.

That makes it easier to update state if it’s an object. No need for functions or object spread syntax.

const [state, setState] = useState({ person: { firstName: '', lastName: '' })

setState({ person: { firstName: 'Tom', lastName: 'Jerry' } })

The setState Hook also doesn’t merge objects. That way, you overwrite the previous state. You can still use object spread syntax to append the new state into the old values. But it’s not necessary.

I find the second solution easier.

Further Reading