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.
- A component requests data.
- If the data is in the cache, it's returned immediately (it's "stale"). The UI can render instantly.
- In the background, a network request is sent to "revalidate" that data.
- 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:
- The user performs an action.
- You immediately update the client-side cache with the new, "optimistic" state. The UI re-renders instantly.
- The actual API request is sent.
- If it succeeds, you invalidate the query to fetch the real data from the server, confirming the change.
- 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.