Sub topic 2
Designing Query Keys and Keeping Server Data Fresh
Assume you know JavaScript and TypeScript, React hooks, async/await, and basic HTTP status codes. This chapter assumes a QueryClientProvider already wraps the React application.
Designing query keys
A query key is a serializable array that identifies one cached result. Include every value that changes the request.
useQuery({
queryKey: ['todos', { status: 'open', page: 1 }],
queryFn: () => fetchTodos({ status: 'open', page: 1 }),
})A different status or page creates a different cache entry. Keep the same structure everywhere. ['todos', 1] and ['todo', 1] are unrelated keys.
How freshness and cleanup work
staleTime controls how long data is considered fresh. During that period, TanStack Query can return cached data without immediately refetching it. The default is zero, so fetched data becomes stale immediately.
gcTime controls how long inactive cache data remains in memory. It does not delete data that a mounted component still uses. The default is five minutes.
Refetching and retries
When stale data is used, TanStack Query can refetch on events such as mounting, window focus, or reconnecting. Failed queries retry automatically on the client, usually three times, with increasing delays. Disable or customize retries when repeated requests would be harmful or misleading.
Mutations and invalidation
A mutation changes server data. After it succeeds, invalidate related queries. Invalidation marks matching cache entries stale and refetches active ones.
import { useMutation, useQueryClient } from '@tanstack/react-query'
export function AddTodo() {
const client = useQueryClient()
const mutation = useMutation({
mutationFn: async (title: string) => {
const response = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!response.ok) throw new Error('Could not add todo')
return response.json()
},
onSuccess: () => {
client.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<button disabled={mutation.isPending}
onClick={() => mutation.mutate('Read documentation')}>
Add todo
</button>
)
}The prefix ['todos'] matches list queries such as ['todos', { page: 1 }]. Invalidate a narrower key when only one resource changed.
Exercise
What should the query key contain for a search request whose results depend on term and page?
Show answer
Use a key such as ['search', { term, page }], so each parameter combination has its own cache entry.