Understanding State Immutability in React
Why You Shouldn’t Mutate State Directly
In React, you should never modify state directly because:
- React won’t recognize the change: Direct mutations don’t trigger re-renders
- Predictability issues: It can lead to hard-to-track bugs in your application
- Performance optimizations: React relies on state immutability for efficient updates
Bad Practice: Direct Mutation
// ❌ Wrong - directly mutating state
this.state.counter = this.state.counter + 1;
Good Practice: Using setState()
// ✅ Correct - using setState()
this.setState({ counter: this.state.counter + 1 });
For Functional Components with Hooks
With the useState hook, you should use the setter function:
const [count, setCount] = useState(0);
// ❌ Wrong
count = count + 1;
// ✅ Correct
setCount(prevCount => prevCount + 1);
Handling Objects and Arrays
When working with complex state (objects, arrays), always create new references:
// For objects
this.setState(prevState => ({
user: {
...prevState.user,
name: 'New Name'
}
}));
// For arrays
this.setState(prevState => ({
items: [...prevState.items, newItem]
}));
Remember that setState()
may be asynchronous, so if you need to update state based on previous state, use the function form shown above.