Advanced React 08 · Ecosystem
Data fetching
Why fetch in useEffect isn’t enough, TanStack Query, Suspense and use().
Loading lesson…
Advanced React 08 · Ecosystem
Why fetch in useEffect isn’t enough, TanStack Query, Suspense and use().
Loading lesson…
Imagine an office where five people need to know a supplier's current prices. Each of them calls on their own and copies the price list into their notepad. The supplier gets five identical phone calls. A week later the supplier changes the prices – and the office has five notepads with old prices that nobody knows are old.
That's the essence of server data: it isn't yours. You only have a copy of it, which can go stale at any time. Local state (an open menu, the text in a field) is your own notebook – you know exactly what's in it. Server data is a copied price list. So it needs things local state doesn't:
That's why a better office has a noticeboard with a keeper. Whoever needs the price list looks at the noticeboard. The keeper calls the supplier only once, knows how old each piece of information is, and calls again when needed. In React, that keeper is the TanStack Query library.
The noticeboard picture guides us through the whole lesson. Folders hang on the noticeboard – each holds a copy of one piece of data (a product list, one user…) – and each folder has a label on its spine that the keeper finds it by. The table shows what each part of the picture is called in code; the picture on the left, the code in the middle, what it does on the right:
| Picture | In code | What it is |
|---|---|---|
| the noticeboard keeper | QueryClient | The object that fetches data, remembers it and knows how old it is. |
| the noticeboard | the cache | All the stored data together. |
| a folder | a query | One piece of data on the noticeboard – say, user no. 2 – along with how old it is. |
| the label on a folder | queryKey | The name a folder is looked up by, such as ['user', 2]. |
| asking for a folder | useQuery | A hook: "give me the data with this label, and if it isn't there, fetch it". |
| crossing out a folder | invalidateQueries | Marking data as invalid so the keeper fetches it again. |
What does it look like in code? Just to give you an idea for now – sections 2 and 3 go through every line in detail:
// 1. THE NOTICEBOARD KEEPER: an object you create once for the whole app (new = create an object, JavaScript 05)const queryClient = new QueryClient()// the noticeboard (cache) is hidden inside queryClient – it has no variable of its own, you don't touch it directly// 2. ASKING FOR A FOLDER: in any component// fetchUser(2) = a function that downloads user no. 2 from the server (we'll write it in section 2)const { data } = useQuery({queryKey: ['user', 2], // the folder's label: "user no. 2"queryFn: () => fetchUser(2), // how to get the data when the folder isn't on the noticeboard yet})// 3. CROSSING OUT A FOLDER: after a change on the server (section 3)queryClient.invalidateQueries({ queryKey: ['user', 2] })
So the keeper is an ordinary object, queryClient, and the noticeboard is its memory. A component doesn't look into it by itself – it asks the keeper through useQuery, and the keeper takes care of the rest: it finds the folder, or fetches it.
An app has two kinds of data, and each belongs somewhere else. The deciding question is: where does the data really live?
useState) is enough for that.So the simple rule is: leave the copy of server data to TanStack Query, keep what only your app knows in state. The table shows typical situations – on the left what you're dealing with, in the middle what with, on the right the section that covers it:
| Situation | Solution | Section |
|---|---|---|
| an open menu, text in a field, a selected tab | state (useState) | lesson React basics 03 |
| a one-off load in a small demo | an effect with ignore | lesson Hooks 01 |
| a list or detail from the server that several components see | useQuery | 2 |
| saving, deleting, a change on the server | useMutation + invalidation | 3 |
| a change should show at once, before the server answers | an optimistic change | 3 |
| waiting described once for a whole part of the page | useSuspenseQuery and Suspense | 4 |
Whenever you show data from the server in an app, you answer three questions – knowingly or not. For now it's enough to understand them with the noticeboard picture; the code for each comes in the section named at the end of its paragraph. Picture an online shop that shows a list of phones and a list of laptops:
queryKey (section 2).staleTime (section 2).invalidateQueries (section 3).You don't need to remember the names in the code yet. The picture is enough: the label (what I want), freshness (how long to trust the copy) and crossing out (what's no longer valid after a change).
From the lesson on effects you know how to load a user like this:
function UserName({ id }: { id: number }) {const [user, setUser] = useState<User | null>(null)useEffect(() => {let ignore = false// fetchUser = a made-up function: downloads the user from the server and returns a PromisefetchUser(id).then((u) => !ignore && setUser(u)) // && = setUser runs only when ignore is falsereturn () => { ignore = true }}, [id])return <span>{user ? user.name : 'Loading…'}</span>}
It works, but each component is that person with their own notepad:
UserName is on the page three times with the same id, three identical requests go out.What you see: On the left, three components that load the same user with useEffect. On the right, three that load it with useQuery. At the bottom, counters of real requests to the server.
Try it:
The takeaway: Loading by hand has no shared memory. useQuery shares one copy, merges identical requests and keeps the data even for components that appear later.
Loading the interactive part…
TanStack Query is a library you add to a project with npm install @tanstack/react-query. You put up the noticeboard once, in the file where the whole app starts:
// main.tsx – once for the whole appimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'const queryClient = new QueryClient() // the manager with the noticeboard (cache); new = create an object (JavaScript 05)createRoot(document.getElementById('root')!).render(// the Provider makes the manager available to the whole app – just like a context's Provider in Hooks 04<QueryClientProvider client={queryClient}><App /></QueryClientProvider>,)
Before we ask the keeper, we need a function that actually downloads the data. In part 1, fetchUser was only made up; now we write it in full. Notice there's nothing from React or TanStack Query in it – it's a plain async function with fetch, the kind you know from JavaScript 07:
// api.ts – functions that talk to the server (User = the type { id: number, name: string } defined next to it)export async function fetchUser(id: number): Promise<User> {const response = await fetch(`/api/users/${id}`) // for id = 2 it downloads /api/users/2if (!response.ok) throw new Error(`Server returned ${response.status}`) // 404 or 500 → a real errorreturn response.json() // the response body (JSON) → the user object}
The response.ok check matters for TanStack Query too: the keeper only notices an error when the function throws (the Promise rejects). Without the throw, a 404 response would look like a success.
And then anywhere in the app:
import { useQuery } from '@tanstack/react-query'import { fetchUser } from './api' // our function from the example abovefunction UserName({ id }: { id: number }) {const { data, isPending, isError, error } = useQuery({queryKey: ['user', id], // the label: exactly what I wantqueryFn: () => fetchUser(id), // how to get it when it isn't on the noticeboard (a function that returns a Promise)staleTime: 60_000, // the information is fresh for a minute (60,000 ms)})if (isPending) return <span>Loading…</span> // the first load is still runningif (isError) return <span>{error.message}</span> // the server returned an errorreturn <span>{data.name}</span> // here the data is there}
useQuery gets an object with three settings and returns an object with the query's state, which you unpack by destructuring:
queryKey – the folder's label: what you want.queryFn – how to get it when it isn't on the noticeboard.staleTime – how long the data is fresh, in milliseconds. The underscore in 60_000 is just a thousands separator for easier reading, JavaScript ignores it: 60_000 is the same as 60000.queryKey: ['user', id] is an array that tells the keeper which folder you're looking for. The first item is a word you make up yourself that says what kind of data it is ('user'). The next items say which piece of it (id = which user). For id = 2 the label is ['user', 2], for id = 3 it's ['user', 3] – two different folders side by side. The label never goes to the server and fetchUser doesn't get it; it's only for the keeper to search the noticeboard. It must be the same everywhere you mean the same data, though – if one component writes ['user', 2] and another ['person', 2], the keeper treats them as two different folders and downloads the user twice.
What happens when id changes in the component:
['user', 2], the folder is on the noticeboard.id changes to 3 → on the next render the label is ['user', 3]. There's no such folder yet, so the keeper calls queryFn and the component is isPending.id goes back to 2 → folder ['user', 2] is still on the noticeboard, the data is there at once, no "Loading…".You don't write a dependency array like with useEffect – the label does its job. Why everything the query depends on belongs in it is covered below in "queryKey: the label on a folder".
queryFn: () => fetchUser(id) is a function that the keeper calls, not you – and only when the folder is missing from the noticeboard or is stale. When the data is fresh, queryFn doesn't run at all. It must return a Promise (JavaScript 07): whatever the Promise returns ends up in data (and TypeScript infers the type of data from it, so you don't write it); when the function throws, you get isError and error.
Why the arrow () => at the start? You're giving the keeper instructions – "when needed, call the supplier and ask for user id" – not a phone call already made. Three ways of writing it that look alike:
queryFn: fetchUser(id), // ❌ fetchUser runs right away, on every render,// and the keeper gets a Promise instead of a functionqueryFn: fetchUser, // ❌ the keeper calls it with its own object (holding the label, for example),// not with id – fetchUser would get the wrong argument (TypeScript reports it)queryFn: () => fetchUser(id), // ✅ an arrow function (JavaScript 02): runs nothing until the keeper calls it;// then it calls fetchUser with the current id and returns its Promise
The order of the ifs matters: first "I have nothing yet", then "error", and only at the end the data. Until the data has arrived, data is undefined. TypeScript knows it – and after both ifs it also knows that data can no longer be undefined (narrowing from TypeScript 02).
Every folder is either fresh or stale. That doesn't mean stale data is wrong – only that it would be worth asking the supplier again. With staleTime: 60_000 it looks like this:
The keeper refreshes a stale folder when a new component that needs it appears, when the user comes back to the browser window (from another tab, say) and when they reconnect to the internet. The default staleTime is 0 – data is stale right after downloading, so it's refreshed at every such opportunity.
Related to this are two flags that are easy to mix up. isPending is true only while you have no data at all – that's the moment for "Loading…". isFetching is true whenever a request is running, including a background refresh when the data is already on screen. It's good for a small "🔄 updating…" icon next to the data, not for hiding the whole page.
What happens when three UserNames with id = 2 appear on the page:
['user', 2]. There's nothing on the noticeboard → the keeper calls queryFn. The component is in the isPending state.staleTime (stale), the keeper also refreshes it in the background.The keeper looks up data on the noticeboard by its label. So it must contain everything the query depends on. The fruit price list, page 2 is a different folder from the vegetable price list, page 1:
// inside a component with a product list (category and page are its props or state)useQuery({queryKey: ['products', { category, page }], // ✅ a change of category or page = a different folderqueryFn: () => fetchProducts({ category, page }), // made up like fetchUser: downloads one page of products})useQuery({queryKey: ['products'], // ❌ all the pages would share one folderqueryFn: () => fetchProducts({ category, page }),})
The label is an array. The keeper compares it item by item: ['products', { category: 'fruit', page: 2 }] is a different folder from ['products', { category: 'fruit', page: 1 }]. An object inside is compared by content, so the order of its properties doesn't matter.
With paging, the list would disappear for a moment after clicking the next page – a new label, a new folder, still empty. That's why you add placeholderData: keepPreviousData: "until the new page arrives, show the old one":
import { keepPreviousData } from '@tanstack/react-query'const { data, isPlaceholderData } = useQuery({queryKey: ['posts', { page }],queryFn: () => fetchPosts(page), // a made-up function: one page of postsplaceholderData: keepPreviousData, // meanwhile show the last page})// isPlaceholderData = true while the old one is shown → you can make it see-through, say
The table sums up all the terms from this section. The top part is the options you give useQuery (in the object in the parentheses), the bottom part the values useQuery returns to you (you pick them by destructuring). The name on the left, where it belongs in the middle, the meaning on the right:
| Term | Where it belongs | Meaning |
|---|---|---|
queryKey | option | The label on the folder. Contains everything queryFn depends on. |
queryFn | option | The function that downloads the data (returns a Promise). The keeper calls it only when the folder isn’t on the noticeboard or is stale. |
staleTime | option | How long the information is fresh, in milliseconds (default 0 → refreshed on every mount or return to the window). |
gcTime | option | How long the noticeboard keeps data nobody uses (default 5 min). Then the folder is thrown out – gc stands for "garbage collection". |
placeholderData | option | What to show before the data arrives. When paging, you put keepPreviousData here = "keep showing the previous page for now". |
retry | option | How many times to try again after an error (default 3). retry: false = give up at once on an error – handy in tests and in challenges where the error should show straight away. |
data | value | The downloaded data. Until it’s there, it’s undefined – that’s why you ask about isPending first. |
isPending | value | We don’t have any data yet (the first load). |
isError | value | true when queryFn failed (and the attempts from retry ran out). |
error | value | That error – its text is in error.message. |
isFetching | value | A request is running right now – even in the background when we already have data (say for a "🔄 refreshing" icon). |
isPlaceholderData | value | true while the data from placeholderData (the old page) is shown instead of the new data. |
refetch | value | A function "download it again right now" – say for a "Try again" button on an error: onClick={() => refetch()}. |
TanStack Query has more options and values (you’ll find them in its documentation), but these are enough for everyday data loading.
So far we've only read data from the server. A real app also changes it: it adds a post, deletes a task, saves a profile. In TanStack Query such a change to data on the server is called a mutation (from the Latin mutare = to change). Reading is a query – "what's in the price list?" –, a change is a mutation – "please change this in the price list".
Why isn't useQuery enough for changes? Because the keeper runs queries by itself and repeatedly: when a component first shows, when you come back to the window, when the data goes stale, and after an error it tries again. For reading that's harmless – reading the price list twice breaks nothing. For a change it would be a disaster: every repeat would add another post or send another payment on the server. A change has to happen exactly once and only when the user asks for it (clicks a button). That's why it has its own hook, useMutation. The table compares the two hooks; on the left the property, in the middle a query, on the right a mutation:
| query (useQuery) | mutation (useMutation) | |
|---|---|---|
| what it does | reads data from the server | changes data on the server (adds, edits, deletes) |
| request method (JavaScript 07) | GET – "I want data" | POST, PUT, DELETE – "I’m sending a change" |
| when it runs | by itself, when a component needs the data | only when you call mutate |
| repeating | as often as you like, nothing happens | never by itself – twice = two posts |
| noticeboard (cache) | the result sits in a folder under a label | stores nothing, has no label |
Just like with reading, we start with a function that actually talks to the server. createPost is a sister of fetchUser from chapter 2 – a plain async function with no React in it. Only it doesn't download data, it sends it, with the POST method from JavaScript 07:
// api.ts – next to fetchUser (Post = the type { id: number, title: string })export async function createPost(title: string): Promise<Post> {const response = await fetch('/api/posts', {method: 'POST', // POST = I'm sending new data (without method it'd be GET = I want data)headers: { 'Content-Type': 'application/json' }, // a header: "the body is JSON"body: JSON.stringify({ title }), // { title } = { title: title } → the text {"title":"A new post"}})if (!response.ok) throw new Error(`The server returned ${response.status}`) // the server refused → a real errorreturn response.json() // the server returns the saved post, now with the id it gave it}
The same two rules apply as for queryFn: it must return a Promise and throw an error when it fails. Without throw TanStack Query would treat a refused post as saved. And whatever the function returns (the saved post) ends up in mutation.data after success – that's how the demo below shows "Added: …".
Now we connect the function to a component. Imagine that elsewhere on the page there's a list of posts reading a query labelled ['posts', { page }] (the keepPreviousData example in chapter 2). When you add a post, the copy of that list on the noticeboard is no longer valid – just like when you call the supplier yourself and order a change. You cross it out, and the keeper gets a new one. That's exactly what the pair useMutation + invalidateQueries does:
import { useMutation, useQueryClient } from '@tanstack/react-query'import { createPost } from './api'function NewPost() {const queryClient = useQueryClient() // gets the manager from QueryClientProviderconst mutation = useMutation({// what to do on the server: the createPost function from the example above// (we pass it without (), mutate calls it later)mutationFn: createPost,// onSuccess = a function TanStack Query calls once createPost succeedsonSuccess: () => {// cross out all the folders starting with 'posts'return queryClient.invalidateQueries({ queryKey: ['posts'] })},})return (// mutation.mutate('A new post') = run the change now: it calls createPost('A new post')// (onClick gets an arrow function, so mutate is called only after the click, not right away while rendering)// disabled: while saving (isPending), the button can't be pressed again<button onClick={() => mutation.mutate('A new post')} disabled={mutation.isPending}>{mutation.isPending ? 'Saving…' : 'Add'} {/* different text while saving */}</button>)}
useMutation doesn't send anything yet – it just returns a mutation object with the mutate function ("run the change") and flags like isPending.mutation.mutate('A new post'), which calls createPost('A new post') – whatever you give mutate, mutationFn gets. Unlike useQuery, a mutation doesn't start by itself, it waits for your command. While waiting, isPending is true and the button is disabled, so a second click doesn't send the post twice. (The text is hard-coded here to keep it simple; in the demo below you type it into the form field.)onSuccess, and invalidateQueries marks folders as stale. Labels are compared by their beginning: ['posts'] matches ['posts', { page: 1 }], ['posts', { page: 2 }] and all the others – every page of the list is crossed out at once.return before invalidateQueries good for? It returns a Promise that's fulfilled once the list has been reloaded. When you return it, the mutation stays isPending until the new list arrives – so the "Saving…" button doesn't go away before the new post appears.A mutation has the same flags as a query: mutation.isPending (saving), mutation.isError and mutation.error (the server refused the change). So you can show the error below the button, for example:
{mutation.isError && <p role="alert">{mutation.error.message}</p>} // role="alert" = a screen reader reads the message at once
What you see: At the top, a form for a new post (a mutation), at the bottom a paged list (a query with ['posts', { page }]). While data is being refreshed, "🔄 updating…" shows.
Try it:
keepPreviousData nothing flashes.posts folders.The takeaway: Queries read from the noticeboard, mutations change the server and cross out old copies. The keeper takes care of the rest.
Loading the interactive part…
Invalidation has one drawback: you see the change only once the server answers and the list is downloaded again. For adding a post that's fine – "Saving…" for a second is OK. But for small things like ticking off a task or a like, the user expects the tick to appear right after the click. That's why there's the optimistic change: you optimistically assume the server will accept the change and show it at once. If it rejects it after all, you put everything back.
You know the principle from useOptimistic in Advanced React 01. Only now you don't edit component state but the copy on the noticeboard – so every component reading that folder sees the change. Besides onSuccess, useMutation offers more functions TanStack Query calls at a certain moment. They're called hooks too – a different meaning from React hooks, here it just means "places where your code hangs":
| Hook | When TanStack Query calls it | What you do in it |
|---|---|---|
onMutate | right after mutate, before the request is sent | back up the copy and change it |
onError | when the server rejects the change | put the backup back |
onSettled | at the end, after success and after an error | cross out the folder so it matches the server |
The table shows the hooks in the order they come. This is how it looks on a task list where a click on a checkbox toggles whether a task is done. It's the whole component – loading the list, the mutation and the JSX – and below the example we'll take it apart piece by piece:
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { fetchTodos, toggleTodo } from './api'// fetchTodos() = a function in api.ts that downloads the task list from the server (GET like fetchUser)// toggleTodo(id) = a function in api.ts that toggles done/not done on the server (POST like createPost)// Todo = the type { id: number, text: string, done: boolean }function TodoList() {const queryClient = useQueryClient() // the noticeboard manager (as with createPost above)// THE LIST: reads the folder ['todos'] – just like useQuery in UserName aboveconst { data: todos, isPending, isError, error } = useQuery({queryKey: ['todos'], // the folder's labelqueryFn: fetchTodos, // without () – TanStack Query calls it when needed})const toggle = useMutation({// what gets sent to the server – it gets the id from toggle.mutate(todo.id)mutationFn: (id: number) => toggleTodo(id),// 1) RIGHT AFTER THE CLICK (before the request goes out) – gets the same idonMutate: async (id: number) => {// a) stop a load of the list that's running right now, so it doesn't overwrite the editawait queryClient.cancelQueries({ queryKey: ['todos'] })// b) the backup: what's in the folder now (in case the server rejects the change)const previous = queryClient.getQueryData<Todo[]>(['todos'])// c) edit the copy on the noticeboard – the task gets ticked on screen at oncequeryClient.setQueryData<Todo[]>(['todos'], (old) =>old?.map((todo) =>todo.id === id? { ...todo, done: !todo.done } // the clicked task: a copy with the opposite done: todo, // the other tasks unchanged),)// d) pass the backup on – the other hooks get it as contextreturn { previous }},// 2) WHEN THE SERVER REJECTS IT: put the backup back into the folderonError: (err, id, context) => {queryClient.setQueryData(['todos'], context?.previous)},// 3) ALWAYS AT THE END (after success and error): cross out the folder so the copy matches the serveronSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),})if (isPending) return <p>Loading…</p> // the list is still downloading for the first timeif (isError) return <p>{error.message}</p> // the list couldn't be downloadedreturn (<><ul>{todos.map((todo) => (<li key={todo.id}><label><inputtype="checkbox"checked={todo.done} // the tick = done from the folder (new right after onMutate)onChange={() => toggle.mutate(todo.id)} // click = start the mutation with this task's id/>{todo.text}</label></li>))}</ul>{/* the server rejected the change: onError has already restored the backup, here we just say why */}{toggle.isError && <p role="alert">{toggle.error.message}</p>}</>)}
What happens when the user clicks the checkbox of the task with id 3:
toggle.mutate(3) starts the mutation. The number 3 goes to mutationFn and to all the hooks – that's why onMutate and onError have an id parameter.onMutate(3). It backs up the list and switches task 3 to done in the folder. All components that read the folder ['todos'] through useQuery – here TodoList itself – re-render with the new todos and the tick shows at once.mutationFn(3) called and the request flies to the server.onError is called and puts the backup back into the folder – the tick disappears.onSettled finally crosses out the folder and the list is fetched again. Now the screen shows exactly what the server has.| Moment | task 3 on the server | task 3 in the folder (what the user sees) |
|---|---|---|
| before the click | not done | not done |
after onMutate | not done | done |
| the server accepted the change | done | done |
…or rejected it → onError | not done | not done – backup restored |
after onSettled | same as the row above | fetched again from the server |
The table reads top to bottom like a timeline – it's the same table as for the likes with useOptimistic in lesson Advanced React 01. The only difference is that here React doesn't do the "undo" for you: you save the backup and put it back yourself.
And now the individual parts of the code:
useQuery at the top downloads the list into the folder ['todos'] and returns it as todos (data: todos in the destructuring just renames data to a clearer name). The mutation then changes the same folder – that's why the label in useQuery and in all the hooks must be the same: ['todos'].todos with map (with a key from lesson React basics 02) and the checkbox shows todo.done. When onMutate or onError changes the folder, useQuery returns the new todos and the tick re-renders by itself. The <label> around the checkbox and the text is there for accessibility: a screen reader reads which task the checkbox belongs to, and you can click the text too. Below the list is the message from toggle.error when the server rejects the change – the same flags as mutation above.getQueryData and setQueryData – the first reads what's in the folder now, the second writes something else there. You can give setQueryData a new value directly (that's what onError does with the backup), or a function that gets the old value (old) and returns a new one – just like an updater in useState. <Todo[]> tells TypeScript what type is in the folder; it doesn't know by itself, because a folder can hold anything.old?.map reads from the outside in: old?.map(…) goes through the list so far and creates a new array (?. from JavaScript 06 – if the list isn't on the noticeboard yet, it returns undefined instead of an error). For every task it asks todo.id === id: for the clicked one it returns the copy { ...todo, done: !todo.done } – all properties the same, only done flipped; the other tasks it returns as they are. The new array and the new object are needed because the copy on the noticeboard must not be changed directly (immutability from JavaScript 09) – otherwise neither TanStack Query nor React would notice the change.cancelQueries is there because of a race of responses. Picture this: a second ago the task list started downloading (say because you came back to the window). Now you tick task 3 and onMutate switches it in the folder. A moment later the older download arrives – with a list where task 3 isn't done yet – and writes it into the folder. The tick disappears even though the server rejected nothing. cancelQueries cancels such a running download and await waits until it has really stopped; that's why onMutate is marked async.context – whatever onMutate returns, the other hooks get as context. That's how the backup previous gets to onError, even though it's a different function. onError gets three parameters: the error (err), what went into mutate (id), and context. Here we only need the third, but parameters are passed by position, so you have to write the first two. context?.previous reads the backup only if context exists.onSettled is called after success and after an error. However it turned out, the folder ends up matching the server – if the server added something to the task (say the date it was finished), you'll see it.A simple rule: use an optimistic change for small changes that almost always go through (a tick, a like, a rename). For everything else – a new post, a payment, a deletion – plain invalidation from the start of this section is enough: it's shorter and the user knows when the change was really saved. You'll try the whole procedure in the Optimistic likes challenge at the end of the lesson.
The main thing first, so you don't get lost in this chapter: TanStack Query still gets and remembers the data. This chapter doesn't bring a new way of downloading; it answers a different question – where to show "Loading…" and the error. For any data from the server you deal with two separate things:
| Question | Answer | Where in the lesson |
|---|---|---|
| Who downloads the data, remembers it and refreshes it? | TanStack Query (or a router loader) | chapters 2 and 3 |
| Where are the waiting and the error shown? | either in every component (if (isPending)), or once, one level up (Suspense) | this chapter |
The table shows that Suspense doesn't replace TanStack Query – it only handles the second row.
In a restaurant every table can report "I don't have my soup yet", "I don't have my main course yet"… Or the whole section gets a sign saying "being prepared, please wait" and the dishes are brought when they're ready. The second way is clearer – the waiter handles the waiting in one place.
Instead of if (isPending) in every component, you can describe the waiting once, one level up: wrap part of the tree in React's <Suspense fallback> component. The components inside then simply "have" the data. This is called a declarative style: you describe what should be shown ("this sign while waiting") instead of writing how to arrange it step by step (check a flag, a branch with "Loading…", a branch with the data) in every component separately. The fallback is what's shown in place of the content while waiting. Errors are then caught the same way, once, one level up, by an error boundary (ErrorBoundary from Advanced React 05).
With TanStack Query you arrange it with one word: instead of useQuery you write useSuspenseQuery. The label and the queryFn stay the same, the noticeboard works the same, only who shows the waiting and the error changes. Compare both versions of the same component:
// ❶ useQuery (chapter 2): the component handles waiting and errors itselffunction UserProfile({ id }: { id: number }) {const { data: user, isPending, isError } = useQuery({queryKey: ['user', id],queryFn: () => fetchUser(id),})if (isPending) return <p>Loading…</p> // every component has its own "Loading…"if (isError) return <p>Error</p> // … and its own errorreturn <h2>{user.name}</h2>}// ❷ useSuspenseQuery: the component handles only the datafunction UserProfile({ id }: { id: number }) {const { data: user } = useSuspenseQuery({ // the same label and queryFn as abovequeryKey: ['user', id],queryFn: () => fetchUser(id),})return <h2>{user.name}</h2> // no ifs – the code gets here only once the data is there}// … and you describe waiting and errors once, one level up, e.g. for the whole page:function UserPage({ id }: { id: number }) {return (<ErrorBoundary fallback={<p>Couldn't load the user</p>}> {/* an error anywhere inside → this message */}<Suspense fallback={<p>Being prepared…</p>}> {/* waiting anywhere inside → this sign */}<UserProfile id={id} /><UserPosts id={id} /> {/* a made-up second component with useSuspenseQuery – both share one sign */}</Suspense></ErrorBoundary>)}
Version ❷ pays off when a page has several components with data and you don't want each of them to flash its own "Loading…" – instead of several small signs there's one big one. As a bonus, data is never undefined, so TypeScript asks for no checks. Version ❶ is simpler when only one thing on the page is waiting or when you want to show the waiting right at a particular component.
How does a component with useSuspenseQuery tell React "I'm still waiting"? React itself can do the same with the use hook, given a Promise. Yes, it's the same use you read a context with in Hooks 04 – how it can do both is explained below the example. You won't write it yourself often – but you'll meet it in Next.js (a framework on top of React) and in some libraries, where someone else prepares the Promise with the data for you. So it's worth knowing how it works.
Recall from JavaScript 07 what a Promise is: a ticket you get right away when you order, while the food (the data) comes later. When you call fetchUser(2), the download starts and the function immediately returns a Promise – "user no. 2 is on the way". We'll call such a Promise userPromise (a promise of a user). The use function gets exactly this ticket and waits until the data for it arrives.
There's one catch (the warning below the demo goes through it in detail): the ticket must not be created inside the component that waits for it, or it would order again on every render. That's why someone else makes it and the component gets it as a prop. Here it's made by a small function getUser, which remembers the tickets in a Map from Hooks 02:
// 1. WHO ORDERS: getUser returns a Promise with the user and remembers itconst cache = new Map<number, Promise<User>>() // id → a Promise with the user; outside components, so it survives rendersfunction getUser(id: number): Promise<User> {if (!cache.has(id)) cache.set(id, fetchUser(id)) // the first time: start downloading and store the Promisereturn cache.get(id)! // every time: return THE SAME stored Promise}
import { Suspense, use } from 'react'// 2. WHO WAITS: the component gets a ready ticket (userPromise) as a prop and downloads nothing itself// Promise<User> = a promise that a User object will come in timefunction UserProfile({ userPromise }: { userPromise: Promise<User> }) {const user = use(userPromise) // wait for the data on the ticket; the code gets here only once the data is therereturn <h2>{user.name}</h2>}// 3. THE PARENT: orders (getUser(id) returns a Promise) and passes the ticket on<ErrorBoundary fallback={<p>User not found</p>}><Suspense fallback={<p>Being prepared…</p>}><UserProfile userPromise={getUser(id)} /></Suspense></ErrorBoundary>
use(userPromise) checks whether the Promise is done. If not, the component says "still waiting" and React shows the fallback of the nearest Suspense above it instead.use returns the data.ErrorBoundary from Advanced React 05).In practice you don't write a cache like getUser by hand – a library makes it (TanStack Query, the router); we show it here so you can see what happens inside.
use is a hook – it starts with use and is called in a component, just like useState. Unlike the other hooks, though, it has no single fixed job: it looks at what you give it and behaves accordingly. Like a card reader at a checkout: tap a payment card and it pays, tap a loyalty card and it adds points. There's one device; what it does depends on the card.
| What you give use | What it does | What it returns | Where in the course |
|---|---|---|---|
a context (use(ThemeContext)) | finds the nearest Provider above the component and listens to it; when its value changes, it re-renders the component | the value from the Provider | Hooks 04 |
a Promise (use(userPromise)) | if it isn't done yet, the component says "I'm waiting" and the fallback of Suspense shows; if it fails, an error boundary catches the error | the data, once the Promise arrives | this section |
Each row of the table is one "card": the first column is what you put into use, the others what it does with it and what it gives you back.
use is exceptional in one more way: it may be called inside an if or after a condition. Remember from lesson React basics 03 why the other hooks may not? React writes their values into the component's notebook on lines by the order of the calls – if one useState were skipped once, the lines would shift. But use doesn't need a line of its own in the notebook: it remembers nothing between renders itself, it only reads what you give it. The Provider remembers the context, a cache remembers the Promise (like getUser above). That's why it doesn't matter if it's called once and not the next time:
function Greeting({ showName, userPromise }: { showName: boolean; userPromise: Promise<User> }) {if (!showName) return <p>Hi!</p> // here the component ends and use isn't called at allconst user = use(userPromise) // ✅ use may come after a condition – with useState this would be a bugreturn <p>Hi, {user.name}!</p>}
The first rule of hooks still applies to use, though: call it only in a component or in a custom hook, not in an onClick or in an ordinary function outside the component.
What you see: Buttons #1–#5 and the profile of the selected user. The profile uses use(promise), the waiting is handled by Suspense, errors by an error boundary. Switching is wrapped in startTransition.
Try it:
The takeaway: The component with the data handles neither waiting nor errors. Suspense describes the waiting, the error boundary the errors – one level up and in one place.
Loading the interactive part…
The loader from Advanced React 07 downloads the data before the page shows – no "Loading…" and no waterfall. But it remembers nothing by itself: it downloads again on every visit to the page and knows nothing about mutations and invalidation. The noticeboard is exactly the opposite – it remembers, refreshes and invalidates, but starts getting the data only when the component renders. They work best together: the loader just pins the data on the noticeboard and the component takes it from there.
For the loader and the component to talk about the same folder, they must get the same queryKey and queryFn. So you don't write them twice, you wrap them into one function with the queryOptions helper:
// ─── file src/queries.ts – you write the query setup once and use it everywhere ───import { queryOptions } from '@tanstack/react-query'// fetchProduct(id) = your function in api.ts that downloads the product from the server// (returns a Promise with an object of type Product = { id: number, name: string, price: number })import { fetchProduct } from './api'export const productQuery = (id: number) =>queryOptions({ queryKey: ['product', id], queryFn: () => fetchProduct(id), staleTime: 60_000 })// productQuery(3) returns the object { queryKey: ['product', 3], queryFn: …, staleTime: 60000 }
The loader then calls queryClient.ensureQueryData – "make sure this data is on the noticeboard". The component uses the same query. Here are all the files together – the noticeboard manager, the page with its loader and main.tsx, which joins the router and the noticeboard:
// ─── file src/queryClient.ts – the noticeboard manager in a file of its own ───import { QueryClient } from '@tanstack/react-query'// export: a loader isn't a component, so it may not call useQueryClient() (rules of hooks) –// that's why it imports the manager from here. Components get it from QueryClientProvider in main.tsx.export const queryClient = new QueryClient()// ─── file src/pages/ProductPage.tsx – the loader and the page side by side ───import { useParams, type LoaderFunctionArgs } from 'react-router'import { useSuspenseQuery } from '@tanstack/react-query'import { queryClient } from '../queryClient'import { productQuery } from '../queries'// 1. THE LOADER (Advanced React 07): the router calls it before it shows the pageexport async function productLoader({ params }: LoaderFunctionArgs) {const id = Number(params.productId) // the address /products/3 → params.productId = "3" → the number 3// ensureQueryData: is it on the noticeboard? Done. Isn't it? Download it, pin it and wait for it.await queryClient.ensureQueryData(productQuery(id))return null // we return nothing – the data is already on the noticeboard}// 2. THE PAGE: the same label → the data is already on the noticeboardexport function ProductPage() {const { productId } = useParams() // the same "3" from the address (Advanced React 07)// useSuspenseQuery (the start of chapter 4): data is never undefined – and here it doesn't even waitconst { data: product } = useSuspenseQuery(productQuery(Number(productId)))return (<article><h2>{product.name}</h2><p>Price: ${product.price}</p></article>)}// ─── file src/main.tsx – the router and the noticeboard together ───import { createRoot } from 'react-dom/client'import { createBrowserRouter, RouterProvider } from 'react-router'import { QueryClientProvider } from '@tanstack/react-query'import { queryClient } from './queryClient'import { ProductPage, productLoader } from './pages/ProductPage'const router = createBrowserRouter([{path: '/products/:productId',loader: productLoader, // 1. the loader first: data onto the noticeboardelement: <ProductPage />, // 2. then the page: data from the noticeboard},])createRoot(document.getElementById('root')!).render(// the same queryClient goes to the components (through the Provider) and to the loader (through the import)<QueryClientProvider client={queryClient}><RouterProvider router={router} /></QueryClientProvider>,)
Why does queryClient get a file of its own when in chapter 2 main.tsx created it directly? Two places need it: the components get it through QueryClientProvider and the loader has to import it. If it lived in main.tsx, the page would import main.tsx and main.tsx would import the page – the files would point at each other in a circle. A separate file that both import is simpler and, above all, guarantees there's one noticeboard. If the loader had its own new QueryClient(), it would pin the data on a different noticeboard from the one the page reads, and all the effort would be wasted.
What happens when the user opens a product's detail:
ensureQueryData finds nothing on the noticeboard, downloads the product and pins it. Only then does the router show ProductPage – and it takes the product from the noticeboard, without waiting.ensureQueryData finds the product on the noticeboard, so the loader doesn't wait at all and the page is there at once.invalidateQueries from section 3 is enough – the noticeboard downloads the product again and the page refreshes by itself. This is the noticeboard's job: the loader on its own is called only when the page opens, so it doesn't know about a later change on the server. That's why here it only pins the data and the noticeboard takes care of the rest.You can get data in advance without a router too. Before a user clicks a link, they usually point at it with the mouse for a moment – and that moment is enough to start downloading. queryClient.prefetchQuery tells the keeper "start getting this now, even though nobody shows it yet". It renders nothing, it just pins the data on the noticeboard. Thanks to productQuery from the example above, it talks about the same folder as the detail page:
// a list of links to products; productQuery = the same function as for the loader above// Link = the router's link from Advanced React 07function ProductLinks({ products }: { products: Product[] }) {const queryClient = useQueryClient() // the keeper from QueryClientProviderreturn (<ul>{products.map((p) => (<li key={p.id}><Linkto={`/products/${p.id}`}// onMouseEnter = the mouse moved onto the link → start downloading the detail, so it's there right after the clickonMouseEnter={() => queryClient.prefetchQuery(productQuery(p.id))}>{p.name}</Link></li>))}</ul>)}
When ProductPage then calls useQuery(productQuery(id)) (or useSuspenseQuery), the data is already on the noticeboard, or at least on its way – no long "Loading…". If the user just moves the mouse over the link and doesn't click, nothing breaks: the data waits on the noticeboard for a while and then the keeper throws it out (gcTime from section 2).
The difference from ensureQueryData in the loader: prefetchQuery only starts the download and doesn't wait for the data – it returns nothing and doesn't even throw an error. So it suits places where it's just about a head start (hovering), and ensureQueryData places where you really need the data before you go on (a loader).
Functions like productQuery pay off even in an app with no loader and no prefetching. Several places talk about the same product: the component that shows it, the link that prefetches it and the mutation that crosses it out after an edit. Each of them must write exactly the same label, otherwise they're talking about a different folder. Look how easily that goes wrong:
// ❌ not like this – the label and queryFn copied in three places// ProductPage.tsxuseQuery({ queryKey: ['product', id], queryFn: () => fetchProduct(id) })// ProductLinks.tsxqueryClient.prefetchQuery({ queryKey: ['product', p.id], queryFn: () => fetchProduct(p.id) })// EditProduct.tsx – after saving a changequeryClient.invalidateQueries({ queryKey: ['products', id] }) // typo: 'products' instead of 'product'
The typo in the third file throws no error. invalidateQueries just finds no folder labelled ['products', 3], crosses nothing out – and after saving, the user still sees the old price. A bug like that takes a long time to find, because the code "works". The same happens when you change the label one day (say to ['product', 'detail', id]) and forget to update one of the three places.
// ✅ like this – the label and queryFn live only in productQuery (the queries.ts file above)useQuery(productQuery(3)) // in a component: read product no. 3queryClient.prefetchQuery(productQuery(3)) // in advance: start downloading it// after a change: cross it out// invalidateQueries wants only the label, not the whole object → take .queryKey from it (= ['product', 3])queryClient.invalidateQueries({ queryKey: productQuery(3).queryKey })
productQuery(3) is an ordinary function call: it returns the object { queryKey: ['product', 3], queryFn: …, staleTime: 60000 }. That's exactly the object useQuery, useSuspenseQuery, prefetchQuery and ensureQueryData expect, so they get all of it.invalidateQueries downloads nothing, it only crosses out – it needs neither queryFn nor staleTime, just { queryKey }. That's why you take only the object's .queryKey property.queries.ts and all the other places follow by themselves. And a typo is no longer possible: if you wrote prodcutQuery(3), TypeScript would report at once that no such function exists – unlike a typo inside an array, which it doesn't mind.queryOptions also remembers the type of data fetchProduct returns. That's why useQuery(productQuery(3)) knows data is a Product and suggests data.name and data.price to you.At the end of the chapter you have several tools, so let's put them in order. The table shows the situation you're in on the left and what to write on the right. Read it from the top: the first row is the default choice and each next one is only for when the previous one stops being enough.
| Situation | What to use |
|---|---|
| An ordinary component that reads data from the server. | useQuery and if (isPending) / if (isError) in the component. The default choice – enough in most apps, in plenty of big ones too. |
| Several components on a page wait for data and you want one shared "Loading…" sign instead of several. | useSuspenseQuery in the components, Suspense and ErrorBoundary above them. |
| You have a router with loaders and TanStack Query, and the "Loading…" when moving between pages starts holding you up. | a loader with ensureQueryData and useSuspenseQuery in the component (the section above). |
| You want the data to start downloading as soon as the user points the mouse at a link. | prefetchQuery in onMouseEnter, with the same options as useQuery (e.g. productQuery). |
| A smaller app that only reads data and needs no remembering or mutations. | just a loader and useLoaderData, without TanStack Query (Advanced React 07). |
| You're waiting for a component's code, not data: a heavy component (e.g. a chart) is in a separate file that's downloaded only when needed – code splitting from Advanced React 04. | lazy(() => import(…)) with Suspense above it. |
| You don't use TanStack Query and a framework or library prepares the Promise with the data for you (e.g. Next.js). | use(promise) with Suspense above it. |
Two things from the table are worth remembering. Where there's TanStack Query, you don't write use() – always useQuery or useSuspenseQuery; use(promise) is what they do inside. And Suspense is one "please wait" sign for everything: React shows it whether it's waiting for data from useSuspenseQuery, a Promise in use, or code from lazy.
This section puts the lesson together into a template to come back to when you load and change data from the server. You'll find the same pattern in the Cheat sheets on the React tab. The template has five parts, each in a file of its own: the noticeboard (1), labels in one place (2), reading (3), an ordinary change with invalidation (4) and an optimistic change (5) – that one only for small changes that almost always go through.
// ─── file src/queryClient.ts – 1. THE NOTICEBOARD: one manager for the whole app ───import { QueryClient } from '@tanstack/react-query'// export: main.tsx uses it, and so can a router loader (which may not call useQueryClient())export const queryClient = new QueryClient() // the manager with the noticeboard (cache)// ─── file src/main.tsx – make the noticeboard available to components ───import { createRoot } from 'react-dom/client'import { QueryClientProvider } from '@tanstack/react-query'import { queryClient } from './queryClient'import { App } from './App'createRoot(document.getElementById('root')!).render(<QueryClientProvider client={queryClient}> {/* makes the manager available to the whole app */}<App /></QueryClientProvider>,)// ─── file src/queries.ts – 2. LABELS IN ONE PLACE ───import { queryOptions } from '@tanstack/react-query'import { fetchProduct, fetchProducts } from './api'// fetchProducts(category) and fetchProduct(id) = your functions in api.ts that download from the server and return a Promise// Product = the type { id: number, name: string, favorite: boolean }export const productsKey = ['products'] // the start of the label of every product list// the product list of one categoryexport const productsQuery = (category: string) =>queryOptions({queryKey: [...productsKey, { category }], // = ['products', { category }] – everything queryFn depends onqueryFn: () => fetchProducts(category), // how to get the data when it's not on the noticeboardstaleTime: 60_000, // the data is fresh for a minute})// the detail of one product (the same function as with the loader in section 4)export const productQuery = (id: number) =>queryOptions({queryKey: ['product', id],queryFn: () => fetchProduct(id),staleTime: 60_000,})// ─── file src/components/Products.tsx – 3. READING ───import { useQuery } from '@tanstack/react-query'import { productsQuery } from '../queries'export function Products({ category }: { category: string }) {// productsQuery supplies the label, queryFn and staleTime – nothing is copied hereconst { data, isPending, isError, error } = useQuery(productsQuery(category))if (isPending) return <p>Loading…</p> // the first load is still runningif (isError) return <p>{error.message}</p> // the server returned an errorreturn <ul>{data.map((p) => <li key={p.id}>{p.name}</li>)}</ul> // here the data is there}// ─── file src/components/AddProduct.tsx – 4. A CHANGE: save and cross out what's no longer valid ───import { useState } from 'react'import { useMutation, useQueryClient } from '@tanstack/react-query'import { createProduct } from '../api' // createProduct(name) = your function in api.ts (POST)import { productsKey } from '../queries'export function AddProduct() {const queryClient = useQueryClient() // the manager from QueryClientProviderconst [name, setName] = useState('') // the text in the field – form state, not server dataconst mutation = useMutation({mutationFn: createProduct, // what to do on the server (mutate calls it)onSuccess: () => {setName('') // saved → clear the field// cross out every folder starting with 'products' → the lists of all categories load again// return: the button stays "Saving…" until the new list arrivesreturn queryClient.invalidateQueries({ queryKey: productsKey })},})return (<div><label>Name <input value={name} onChange={(e) => setName(e.target.value)} /></label>{/* mutate(name) calls createProduct(name); while saving (or with an empty field) it can't be clicked */}<button onClick={() => mutation.mutate(name)} disabled={mutation.isPending || name === ''}>{mutation.isPending ? 'Saving…' : 'Add'}</button>{/* the server rejected the change → say why; role="alert" = a screen reader reads the message at once */}{mutation.isError && <p role="alert">{mutation.error.message}</p>}</div>)}// ─── file src/components/FavoriteButton.tsx – 5. AN OPTIMISTIC CHANGE (only for small changes) ───import { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { toggleFavorite } from '../api' // toggleFavorite(id) = toggles "favourite" on the server (POST)import { productQuery } from '../queries'// there's a Suspense above the component (section 4), hence useSuspenseQuery – the data is always thereexport function FavoriteButton({ id }: { id: number }) {const queryClient = useQueryClient()const { data: product } = useSuspenseQuery(productQuery(id))const { queryKey } = productQuery(id) // the detail's label: ['product', id]const toggle = useMutation({mutationFn: () => toggleFavorite(id),// a) RIGHT AFTER THE CLICK: stop loading, back up, edit the copy on the noticeboardonMutate: async () => {await queryClient.cancelQueries({ queryKey })const previous = queryClient.getQueryData(queryKey) // it knows the type Product thanks to queryOptionsqueryClient.setQueryData(queryKey, (old) =>old ? { ...old, favorite: !old.favorite } : old, // a copy with the opposite favorite)return { previous } // → the other hooks get it as context},// b) THE SERVER REJECTED IT: put the backup back (vars = what went into mutate, nothing here)onError: (err, vars, context) => queryClient.setQueryData(queryKey, context?.previous),// c) ALWAYS AT THE END: make the copy match the serveronSettled: () => queryClient.invalidateQueries({ queryKey }),})return (// aria-pressed: a screen reader announces whether the button is on (that's why the text doesn't change)<button onClick={() => toggle.mutate()} aria-pressed={product.favorite}>{product.favorite ? '★' : '☆'} Favourite {/* the same text, only the star changes */}</button>)}
queryFn are in one place (queries.ts) and components call productsQuery(…), not a copied array.queryKey contains everything the queryFn depends on (id, filter, page).isPending/isError, or Suspense and an error boundary.useState; you use data directly. (The text in a form field does belong in useState – that isn't server data.)onSuccess and shows the error to the user.onMutate, the undo in onError, invalidation in onSettled.Load the product list with TanStack Query. The loading state and the list are finished.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The first challenge is the move from section 1 to section 2: rewrite loading from an effect to useQuery and add prefetching from section 4. The second tries the optimistic change from section 3 on likes – with a backup in case the server rejects the change.
You'll see how much code disappears – and how many features you gain. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
The complete recipe for an optimistic update with a rollback – exactly as in the TanStack Query documentation. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
queryKey is the label and contains everything the query depends on; staleTime says how long the copy stays fresh.QueryClient, QueryClientProvider, useQuery, fetchProducts)QueryClient, QueryClientProvider, useQuery – from the library @tanstack/react-query: the data fetching and caching library (lesson Advanced React 08).fetchProducts – from the file src/course/fakeApi.en.ts. The course fake API: data and functions pretending to be a server (with a delay, sometimes even with an error). In a real app you would call fetch() here.export interface Product {id: numbername: stringcategory: 'fruit' | 'vegetables' | 'bakery' | 'dairy'price: numberinStock: boolean}export async function fetchProducts(query = '', signal?: AbortSignal): Promise<Product[]> {await sleep(randomDelay())signal?.throwIfAborted()const q = query.trim().toLowerCase()return products.filter((p) => p.name.toLowerCase().includes(q))}
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).