Server State with TanStack Query
Fetch, cache, refetch and mutate API data in client components without hand-written loading flags and effects.
Intermediate · about 5 hours · difficulty 3/5
Learn first: State, Effects and Hooks, Asynchronous JavaScript and fetch
Data that lives on the server (internships, applications, notifications) is different from UI state. It can go stale, needs caching, and is shared between screens. TanStack Query is built for exactly this.
Core ideas
- useQuery with a query key (like ["internships", filters]) fetches and caches data, and tracks loading and error state for you.
- Stale time decides how long data is considered fresh before a background refetch.
- useMutation for creates and updates, followed by invalidating the affected queries so lists refresh.
- Optimistic updates change the UI immediately and roll back if the server fails, useful for likes or bookmarks.
Where it fits with Next.js
Server components can fetch data directly on the server, so you need less client-side fetching than in a pure SPA. TanStack Query still shines for highly interactive client screens: dashboards, infinite scroll, polling and live filters.
Pitfalls
- Copying query results into useState, which breaks caching and freshness.
- Query keys that do not include all the inputs, so changing a filter shows old data.
- Forgetting to invalidate after a mutation.
You are ready to move on when your board loads internships through useQuery, paginates with infinite scroll, and saves bookmarks with an optimistic mutation that rolls back on error.
Key concepts
- Server state vs UI state
- useQuery and query keys
- Stale time and refetching
- useMutation and invalidation
- Optimistic updates
- Infinite queries and pagination
- SWR
Mini project
Connect your internship board to a mock API (json-server or a free public API): list with infinite scroll, details with prefetch on hover, and an optimistic bookmark toggle.
Check yourself
You add a new application with a mutation but the applications list does not update. What did you forget?
Free resources
- TanStack Query (TanStack)
- SWR (Vercel)