Sub topic 1
Why server state is different from client state
Prerequisites
This chapter assumes you know JavaScript and TypeScript, including async/await and Promises. It also assumes you can write React function components with hooks such as useState and useEffect, and that you know basic HTTP, fetch, status codes, and JSON APIs.
Two kinds of state
React state comes in two kinds that behave very differently.
Client state is data your app owns. Examples are whether a menu is open, the text in a form field, or the selected tab. It lives in the browser, changes only when your code changes it, and is always current.
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 set of search results. Your component holds only a copy, and that copy can be out of date the moment it arrives.
| Property | Client state | Server state |
|---|---|---|
| Owner | Your app | A remote server |
| Access | Synchronous | Asynchronous |
| Can become outdated | No | Yes, without notice |
| Shared by other users | No | Often |
| Needs loading and error handling | No | Yes |
What goes wrong with hand-written fetching
The usual first approach is useState plus useEffect:
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(setTodos)
.catch((e) => setError(e.message))
.finally(() => setLoading(false))
}, [])
if (loading) return <p>Loading...</p>
if (error) return <p>{error}</p>
return (
<ul>
{todos.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
)
}This works for a demo. Because the data is server state, it leaves several problems unsolved:
- Two components that need the same todos each send their own request.
- Leaving the page and coming back shows a spinner again, because nothing was cached.
- Nothing refreshes the data when the user returns to the tab.
- A slow response can arrive after a newer one and overwrite it (a race condition).
- Failed requests are not retried.
- After you change data on the server, you must remember to update every copy by hand.
Each problem comes from treating a remote, shared, changeable resource as if it were a local variable.
What a server-state library does
TanStack Query (React Query v5) treats server state as a cache that it manages for you. You describe what data you want and how to fetch it. The library then handles the rest:
- It deduplicates identical requests.
- It stores results in a cache and serves them instantly on later renders.
- It decides when cached data is stale and refetches it in the background.
- It retries failures and tracks loading and error status.
- It gives you tools to update the cache after you change data on the server.
Keep the two kinds apart
Do not copy fetched data into useState or a global store such as Redux. A copy becomes a second source of truth that the library cannot refresh. Keep server state in the query cache. Keep client state, such as a draft title or a filter choice, in useState or a client-state tool.
The next chapters build on this split. You will set up the library, fetch data, and learn how its cache decides when to reload.
Exercise
A todo list is fetched from /api/todos, and the user also types a new todo title into an input. Which of these is server state and which is client state? Name one problem the useEffect version above has with the list.
Show answer
The fetched todo list is server state. The text in the input is client state. Problems with the list include no caching, no sharing between components, no refetch when the tab regains focus, possible race conditions, and no retries.