Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
32

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.

Try a free mock interviewPractice system design problems
Previous

Data Fetching: React Query and SWR

Next

SSR vs CSR: Rendering Trade-offs