Sub topic 1
Why server state is different from client state
Prerequisites
This chapter assumes you know the following:
- JavaScript and TypeScript basics, including
async/awaitand Promises. - React function components and hooks such as
useStateanduseEffect. - Basic HTTP and REST ideas, including
fetchand status codes. - JSON APIs.
You do not need any knowledge of TanStack Query. This chapter explains the problem the library solves. Later chapters show how to use it.
Two kinds of state
Most React apps hold two different kinds of data, and they are often stored the same way.
Client state is data that your app owns. Examples are whether a menu is open, the text in a form field, the selected tab, or the current theme. The browser is the only place this data lives. It changes only when your code changes it, and it is always up to date because nobody else can touch it.
Server state is data that lives on a server and that your app borrows. Examples are a list of todos, a user profile, or a page of search results. Your component holds only a copy, which is a snapshot of the data at the moment it was fetched.
That difference in ownership causes most of the problems in this chapter.
| Property | Client state | Server state |
|---|---|---|
| Where the truth lives | In the browser | On a remote server |
| How you read it | Synchronously, from memory | Asynchronously, over the network |
| Can others change it? | No | Yes: other users, other tabs, background jobs |
| Can it be out of date? | No | Yes, as soon as it is fetched |
| Can reading it fail? | No | Yes: timeouts, 500 errors, offline |
| Shared between components? | Only if you pass or lift it | Often the same data is needed in many places |
The hand-written approach
Most developers first fetch data with useState and useEffect. This is a common version of that code.
import { useEffect, useState } from 'react'
type Todo = { id: number; title: string; done: boolean }
function Todos() {
const [todos, setTodos] = useState<Todo[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
fetch('/api/todos')
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
})
.then((data) => setTodos(data))
.catch((err) => setError(err.message))
.finally(() => setLoading(false))
}, [])
if (loading) return <p>Loading...</p>
if (error) return <p>Something went wrong: {error}</p>
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}This works for a demo. It treats server state like client state: fetch once, store it in useState, and assume it stays correct. Real apps expose several problems.
Problems with this approach
- Race conditions. If a prop or parameter changes while a request is in flight, responses can arrive out of order. An older response can overwrite a newer one. You need cleanup logic with an
ignoreflag or anAbortControllerto prevent it. - No caching. Leave the screen and come back, and the component fetches again and shows a spinner. Two components that need the same todos send two requests.
- Stale data. Nothing tells the component that the server data changed. The copy slowly drifts from the truth.
- No retries. A single dropped connection becomes a permanent error screen unless you write retry logic.
- Duplicated boilerplate. Every component repeats the
loading,error, anddatatriplet. - Writes are manual. After you create or update an item, you must remember to refetch or patch the local copy yourself.
You can solve each problem by hand. The cost is that you end up writing and maintaining a cache, a request deduplicator, and a retry system inside your components.
Storing server data in a global client store
A common next step is to put fetched data into a global store such as Redux or Context. This fixes sharing, but it keeps the other problems. You still decide when to fetch, when to refetch, when to discard old data, and how to track loading and error flags for every endpoint. The store treats the data as if your app owned it.
What server state needs
Because server state is remote, shared, and can go stale, it needs a set of features that client state does not.
- Caching. Keep results so the same data is not fetched twice.
- Deduplication. If several components ask for the same data at the same time, send one request.
- Staleness tracking. Know how old each piece of data is and decide when it should be refreshed.
- Background refetching. Show cached data immediately and update it quietly when the user returns to the tab or reconnects.
- Retries. Try again after temporary failures.
- Request state. Expose pending, error, and success in one consistent shape.
- Mutation support. Provide a standard way to send changes and then update what the UI shows.
- Memory management. Remove data that no component has used for a while.
TanStack Query (also called React Query) is a library that provides these features. It is a cache and a request manager for server state. It is not a replacement for fetch. You still write the function that makes the request, and the library decides when to call it, how to store the result, and when to call it again.
The core idea: a cache keyed by query keys
TanStack Query keeps a cache, which is a store of results indexed by a query key. A query key is an array such as ['todos'] or ['todos', 5] that identifies a piece of server data.
A component asks for data by giving the library two things:
- a key that says which data it wants, and
- a function that knows how to fetch it.
The library checks the cache for the key. If the data is there, it returns it right away. If the data is old, it also fetches fresh data in the background and updates every component that uses that key.
The diagram shows what happens when two components ask for the same key.
The hand-written version cannot do this without extra code, because each component owns its own useState.
The same example with TanStack Query
Here is the earlier component rewritten. You will learn each part in later chapters, so read it only to compare the shape.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function Todos() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}Compare the two versions:
- The three
useStatecalls and theuseEffectare gone. - There is no race condition to manage, because the cache entry for a key always holds the latest result for that key.
- A second component that uses
['todos']shares the same data and the same request. - Retries, background refetching, and cache cleanup happen with no extra code.
The queryFn must throw or return a rejected Promise on failure. fetch does not reject on a 404 or 500 response, so the res.ok check matters. Without it, the library would treat an error response as success.
Deciding what belongs where
Moving to a server-state library does not mean everything goes into it. Use this rule: if the server is the source of truth, it is server state. If only the browser cares about it, it is client state.
| Data | Kind | Where to keep it |
|---|---|---|
| List of todos from `/api/todos` | Server state | TanStack Query |
| Current user profile | Server state | TanStack Query |
| Whether a modal is open | Client state | `useState` |
| Text typed in a search box | Client state | `useState` |
| Search results for that text | Server state | TanStack Query, with the text in the query key |
| Selected sort order | Client state | `useState` or URL parameters |
Search is a useful case. The text in the input is client state. The results are server state. The input value becomes part of the query key, so each distinct search gets its own cache entry.
Edge cases and common mistakes
- Copying query data into
useState. If you writeconst [todos, setTodos] = useState(data), you create a second copy that will not update when the cache refreshes. Readdatadirectly, or derive values from it during render. - Treating cached data as always correct. The cache is a snapshot. It shows what the server said at some past time. Later chapters cover how
staleTimecontrols how long the library trusts that snapshot. - Using it for pure client state. A theme toggle or a form draft gains nothing from a cache and a fetch function.
- Forgetting the error check on
fetch. The library only knows a request failed if your function throws. - Expecting the library to fetch for you. It manages when and how often your function runs. You still write the function.
What comes next
The next chapter sets up the QueryClient and the QueryClientProvider, which hold the cache and make it available to every component. After that, you will fetch data with useQuery, read its status, and design query keys.
Exercise
A search page has a text input, a "sort ascending" checkbox, and a list of results fetched from /api/search?q=.... Which of these are server state and which are client state? Where would the text from the input appear in the TanStack Query setup, and why?
Show answer
The input text and the checkbox are client state, because only the browser owns them (keep them in useState). The results list is server state, because the server is the source of truth and the browser holds a snapshot. The input text should be part of the query key, for example ['search', text], so each distinct search has its own cache entry and a change in the text triggers a fetch for the new key.
Exercise
Name three problems with fetching in useEffect and storing the result in useState that TanStack Query solves, and say which feature solves each.
Show answer
Any three of these. Duplicate requests and lost data when you leave and return are solved by caching and deduplication. Out-of-date data is solved by staleness tracking and background refetching. A single failed request becoming a permanent error is solved by automatic retries. Out-of-order responses overwriting newer data is solved by keying each result to its query key. Repeated loading and error flags are solved by the shared request state (pending, error, success).
Exercise
A teammate writes const [todos, setTodos] = useState(data) right after calling useQuery. After another component adds a todo, this list does not change. Why, and how do you fix it?
Show answer
useState(data) uses its argument only on the first render. It creates a separate copy that the cache cannot update. Fix it by removing the copied state and reading data from useQuery directly, or by computing derived values from data during render.