Sub topic 1
Why Server State Is Different from Client State
Prerequisites
You should know JavaScript and TypeScript fundamentals, including async and await, React function components, hooks, and basic HTTP responses.
Server State and Client State
Client state belongs to the current interface. Examples include whether a menu is open, the text in an input, and which tab is selected. React can usually manage this state with useState.
Server state is data owned by a remote system, such as a list of todos from an API. Your component does not control when that data changes. The network can fail, the data can become outdated, and several components may need the same response.
TanStack Query manages this remote data. It stores responses in a cache, tracks request status, retries failed requests, and coordinates updates between components.
Setting Up QueryClient and QueryClientProvider
A QueryClient owns the query cache and its behavior. QueryClientProvider makes that client available to components below it. Create one client for the application, rather than creating one during every render.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()
export function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}Fetching Data with useQuery
A query is a request for server data. useQuery needs a queryKey, which identifies the cached data, and a queryFn, which loads it. The query function must throw when the response fails.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string }
async function fetchTodos(): Promise<Todo[]> {
const response = await fetch('/api/todos')
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
return response.json()
}
function Todos() {
const result = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
if (result.isPending) return <p>Loading...</p>
if (result.isError) return <p>Error: {result.error.message}</p>
return (
<ul>
{result.data.map((todo) => <li key={todo.id}>{todo.title}</li>)}
</ul>
)
}Handling Pending, Error, and Success States
isPending means the query has no data yet and is waiting for its first result. isError means the query function failed. Otherwise, the query has successful data.
Keep these branches explicit. A loading indicator prevents an empty screen, and an error message gives users a recoverable state. Later chapters distinguish initial loading from background refetching.
Exercise
Why should the queryClient usually be created outside the App component?
Show answer
Creating it once preserves one shared cache. Creating it during every render would discard cached data and reset query behavior.