Andrei Calazans

Don't Fall Into This React Bug

☕️ 1 min read
  1. Unmergeable State
  2. Mergeable State
  3. Conclusion

Unmergeable state

React’s useState setter function does not automatically merge your state. This behavior is different from the class’s setState function.

For example:

// Inside a functional component
[state, setState] = useState({ name: 'Andrei' });

// In a callback. When you call setState:
setState({ age: 12 }); 

What is the resulting state after the setState call?

Current state is: {"name":"Andrei"}

Mergeable State

With Class’ setState the behavior is different:

// Inside a class component
state = { name: 'Andrei' };

// In a callback. When you call this.setState:
this.setState({ age: 12 }); 

Current state is: {"name":"Andrei"}


Don’t be a victim to this change of behavior when you migrate to the useState and useReducer hooks.