Skip to main content

What does immutability mean in the context of NgRx?

Immutability in the context of NgRx is a rule: you cannot change the state directly, you can only create a new one based on the old.

What this means in practice:

Bad (mutating):

ts
state.user.name = 'Maria'; // mutating the object directly return state;

Good (immutable):

ts
return { ...state, user: { ...state.user, name: 'Maria' } };

We don't touch the old state, we create a new copy with the changes.

Why it's needed:

  1. Predictability. The old state always remains available. There are no "magic" changes.
  2. DevTools and time-travel. You can easily roll the state back and see what changed.
  3. Optimization. Angular and selectors see that the object changed (by reference) and update only the necessary parts.

In NgRx:

  • Reducers must be immutable - they always return a new state.
  • Mutating anything can introduce bugs that are hard to trace.

Conclusion: Immutability is the rule "don't break it, recreate it." In NgRx, it ensures cleanliness, transparency, and stability.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.