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:
- Predictability. The old state always remains available. There are no "magic" changes.
- DevTools and time-travel. You can easily roll the state back and see what changed.
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.