0

Why does React advise against directly mutating state?

author
kallyani
easy
0
0

Answer

React recommends not mutating state directly because it can lead to unexpected bugs and incorrect UI updates.

React relies on immutability to detect changes and decide when a component should re-render.


What goes wrong when state is mutated

When state is mutated directly:

  • React may not detect the change
  • Components may not re-render
  • UI can become out of sync with data

Example (Incorrect):

state.count = state.count + 1;

This changes the existing state object instead of creating a new one.


Correct Approach:

setUser({ ...user, name: "Subina" });


Why immutability matters

  • React uses reference comparison to detect changes
  • New objects signal React that state has changed
  • Enables predictable rendering and performance optimizations

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0