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
31

Frontend System Design · Lesson 31 of 86 · 4 min

Data Fetching: React Query and SWR

You need to articulate why useEffect is the wrong tool for server state and how modern libraries solve caching, re-validation, and UI consistency.

The Core Problem: Server State is Not Client State

Your first step in any data-heavy system design question is to distinguish between client state and server state. They have different rules.

Client state is synchronous, owned by the client, and has a single source of truth within your app. Think of a theme toggle or form input. The previous lesson on Redux and Zustand covers this.

Server state is different. It's asynchronous, lives on a remote server, is shared across users, and can become stale without you knowing. Using useEffect and useState to manage it forces you to manually build a caching system, handle race conditions, and decide when to re-fetch. This is complex and error-prone.

The trap: Don't equate server state management with Redux Thunk or Saga. While they handle async actions, they don't provide the built-in caching, deduplication, or re-validation that are the entire point of libraries like React Query and SWR. Treating server data like just another entry in your Redux store is an outdated pattern.

These libraries exist to manage server state for you. They treat the server as the source of truth and your client-side cache as a temporary, synchronized copy.

The Pattern: Stale-While-Revalidate

React Query and SWR are built on a caching strategy called stale-while-revalidate. It's a simple but powerful idea that drastically improves perceived performance.

  1. A component requests data.
  2. If the data is in the cache, it's returned immediately (it's "stale"). The UI can render instantly.
  3. In the background, a network request is sent to "revalidate" that data.
  4. When fresh data arrives, the cache is updated and the UI seamlessly re-renders.

This means the user sees content right away, even if it's a few seconds or minutes old, while the app fetches the latest version behind the scenes.

These libraries also automatically re-fetch data in response to certain events, assuming the data might have changed. The defaults are sensible: on component mount, on window refocus, and on network reconnect. This keeps your app feeling alive without manual polling.

Making the Cache Coherent: Query Keys and Invalidation

The single most important concept to master is the query key. It's the unique identifier for a piece of server state in the cache.

In React Query, a key is an array. For a simple list, it might be ['todos']. For data with parameters, include them: ['todos', { status: 'completed', page: 2 }]. This is the cache's address for that specific query.

The trap: A common mistake is using a key that isn't unique enough. If two different useQuery calls use the same key but fetch different data, they will overwrite each other's cache entries, leading to unpredictable bugs. The query key is the dependency array for your remote data.

When you perform a mutation (a POST, PUT, or DELETE), you need to tell the library that related data is now stale. You don't update the cache by hand. Instead, you invalidate it.

Calling queryClient.invalidateQueries({ queryKey: ['todos'] }) tells React Query: "Any query whose key starts with ['todos'] is now stale. Go re-fetch it the next time it's needed." This is how you ensure data consistency after a user action.

Designing a Responsive UI: Optimistic Updates

For actions like adding a comment or deleting an item, waiting for the server response makes the UI feel slow. Optimistic updates solve this. You update the UI before the API call finishes, assuming it will succeed.

Here's the flow:

  1. The user performs an action.
  2. You immediately update the client-side cache with the new, "optimistic" state. The UI re-renders instantly.
  3. The actual API request is sent.
  4. If it succeeds, you invalidate the query to fetch the real data from the server, confirming the change.
  5. If it fails, you roll back the cache to its previous state and show an error.

This is a trade-off. You gain a snappy UI at the cost of complexity and a potential "flicker" if the update has to be rolled back. In an interview, you should be able to explain this trade-off.

This useMutation example shows how to add a new todo optimistically.

import { useMutation, useQueryClient } from '@tanstack/react-query';

// Assume createTodo is an async function that sends a POST request.
// Assume 'todos' is the query key for the list of todos.

function AddTodoForm() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: createTodo,
    // onMutate runs before the mutation function.
    onMutate: async (newTodo) => {
      // Cancel any outgoing refetches so they don't overwrite our optimistic update.
      await queryClient.cancelQueries({ queryKey: ['todos'] });

      // Snapshot the previous value.
      const previousTodos = queryClient.getQueryData(['todos']);

      // Optimistically update to the new value.
      queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);

      // Return a context object with the snapshotted value.
      return { previousTodos };
    },
    // If the mutation fails, use the context we returned from onMutate to roll back.
    onError: (err, newTodo, context) => {
      queryClient.setQueryData(['todos'], context.previousTodos);
    },
    // Always refetch after error or success to ensure server state is correct.
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  // ... form JSX to call mutation.mutate(newTodo)
}

This code is declarative. You're not writing if/else logic to manage state; you're telling the library how to handle each stage of the mutation lifecycle.

Try it

Take a simple fetch call inside a useEffect hook in one of your projects. Refactor it to use useQuery or useSWR. Add a button that performs a mutation and then correctly invalidates the query to see the list update.

Next: Now that you're managing server state, you need to handle client state updates without bugs. We'll cover how to work with Immutable Data in Frontend State.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

State Patterns: Redux, Zustand and Context

Next

Immutable Data in Frontend State