Frontend System Design · Lesson 32 of 86 · 4 min
Immutable Data in Frontend State
This topic separates candidates who just use frameworks from those who understand how they work. Get this right to show you can write performant, predictable code.
Why immutability is a performance lever
When an interviewer asks how immutability helps performance in a framework like React, your answer is about one thing: cheap change detection.
Modern UIs re-render when state or props change. With mutable data, the only way to know if an object has truly changed is to deeply compare its old and new versions. This is slow and scales poorly with the size of your state.
Immutability changes the game. Instead of modifying data, you create a new version. This means a change is signaled by a new object reference. Comparing two references (oldState === newState) is an O(1) operation. It's instant.
This is the mechanism that powers React.memo, PureComponent, and hooks like useMemo. They perform a shallow comparison of props. If the references haven't changed, React can safely skip re-rendering an entire component tree, which is a massive performance win.
The interview angle: Explain that immutability allows you to trade a potentially expensive deep comparison for a cheap reference check. This is the key to unlocking UI framework optimizations and preventing wasted renders.
How to update nested state without bugs
The most common place developers slip up is with nested data. The spread syntax (...) only creates a shallow copy. If you have an object inside an object, you must copy every level on the path to the value you are changing.
The trap: Forgetting to spread a nested object. If you only spread the top level, the nested object's reference remains the same. Frameworks won't detect the change, leading to stale UI and bugs that are hard to trace.
This reducer pattern is the canonical example. Notice how TOGGLE_TODO has to spread both the state and the specific todo object being updated.
interface Todo {
id: string;
text: string;
completed: boolean;
}
interface AppState {
todos: Todo[];
filter: 'all' | 'active' | 'completed';
}
type Action =
| { type: 'ADD_TODO'; payload: { text: string } }
| { type: 'TOGGLE_TODO'; payload: { id: string } };
function appReducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'ADD_TODO':
// Return a new state object...
return {
...state,
// ...with a new todos array inside.
todos: [
...state.todos,
{
id: String(Date.now()),
text: action.payload.text,
completed: false,
},
],
};
case 'TOGGLE_TODO':
return {
...state,
// Create a new array with map...
todos: state.todos.map(todo =>
// ...and if the todo matches, return a new todo object.
todo.id === action.payload.id
? { ...todo, completed: !todo.completed }
: todo // Otherwise, return the original, unchanged todo.
),
};
default:
return state;
}
}
In the TOGGLE_TODO case, we create a new todos array. For every item in that array, we either keep the original object reference (if it's not the one we're changing) or create a new object for the one we are. This is correct and efficient.
The structural sharing optimization
A common objection to immutability is the perceived cost of creating new objects and arrays on every change. This is where structural sharing comes in.
When you create a new version of a data structure, you only create new copies of the parts that changed. The rest of the structure points to the exact same data in memory as the original.
This means the memory and performance cost is proportional to the size of the change, not the size of the entire state. For a large state object, updating one key is very cheap.
This diagram shows an update to a user's name. The address object, being unchanged, is shared by reference between the old and new state. No new memory is allocated for it.
This makes immutable updates practical even for very large and complex state trees.
When to reach for a library
Manual immutable updates with spread syntax work well, but they can get verbose and error-prone with deeply nested state (e.g., state.a.b.c.d = 1).
This is the problem libraries like Immer and Immutable.js solve.
Immer is the pragmatic choice for most projects. It lets you write simpler, "mutating" code inside a special function, and it produces a correct immutable update with structural sharing under the hood. It's less boilerplate and easier to read.
import { produce } from "immer";
const nextState = produce(baseState, draft => {
draft.user.profile.settings.theme = "dark";
});
Immutable.js provides a set of dedicated immutable data structures (Map, List, etc.). It offers performance guarantees and a rich API, but it comes with a steep learning curve. You have to convert your data to its format (fromJS) and back (toJS), which can be cumbersome and add overhead.
In an interview: Acknowledge the boilerplate of manual updates. Position Immer as the standard solution for simplifying this. Mention Immutable.js as a more heavyweight option for performance-critical applications where its specific data structures offer a benefit, but be aware of its API overhead.
Avoid JSON.parse(JSON.stringify(obj)) for deep clones. It's slow, inefficient, and breaks data types like Date, Map, Set, and functions. It's a sign of not understanding proper state management.
Try it
Given a state object like { users: { byId: { 'u1': { name: 'A' } }, allIds: ['u1'] } }, write a function that immutably updates the name of user u1 to 'B'. Make sure you correctly create new users, byId, and u1 objects.
Next: We'll discuss when the server should render your app versus when the client should in "SSR vs CSR: Rendering Trade-offs".
Lock it in — apply this lesson under interview conditions.