foundation

Immutability

Use structural sharing and immutable updates so change detection, history, and debugging stay reliable.

Immutable updates return new references for changed branches while structurally sharing unchanged subtrees. React, Redux, and time-travel debugging rely on reference inequality to detect change.

					const state = { user: { id: 'u1' }, prefs: { theme: 'dark' } };
const next = {
  ...state,
  prefs: { ...state.prefs, theme: 'light' },
};
// state !== next; state.user === next.user
				

Redux Toolkit uses Immer so reducers can write "mutating" syntax that produces immutable drafts. MobX often mutates observables directly — different change model, same need for explicit update boundaries.

The trade-off is predictable change detection and time-travel debugging versus allocation cost and verbose update code.

On interviews: predict which references change after a nested update; explain structural sharing.

Common pitfalls: in-place array `sort`/`splice`, mutating nested objects in `useState`, and spreading shallow copies while leaving inner objects shared and mutated.

Checklist:

  • Replace changed branches; share the rest.
  • Copy arrays/objects before in-place methods.
  • Use Immer or helper utilities for deep trees.
  • Test reference equality assumptions in selectors.