September 6, 2026
Setting Up React Query and Axios the Way I Use Them, Line by Line


Reference: TanStack Query (React Query) docs ยท Axios docs ยท Integrating React Query with Server Actions in Next.js 15 - CodeMint ยท React Query, Modern Modal Forms and Reusable Custom Data table - CodeMint
This guide walks through the exact files I use to fetch and mutate data in my Next.js apps: the Axios instance (config/axios.ts), the React Query provider (app/providers/ReactQueryProvider.tsx), and the query hooks (hooks/useStudents.ts). It starts with the installation commands (for npm, pnpm and bun), then gives every line its own plain-language explanation and a real-life example so you know not just what the code does, but why it exists.
Who this is for: you're comfortable with basic React and Next.js, and you roughly know what an API call is. You don't need any prior React Query experience, every piece is explained from scratch.
Backstory
Data-fetching bugs are sneaky. The code looks simple - call an API, show the data, submit a form, but almost every line exists because of a specific, real problem someone ran into first.
Here's one of them. Imagine a school management system. A registrar adds a new student, clicks Save, and the form closes. But the students list on screen still shows the old list, without the new student. The registrar thinks the save failed, so she registers the same student again. Now the database has two copies of the same child.
Nothing was wrong with the database. The screen was simply showing old data. That one bug is exactly what the last line of the mutation hook in this guide (invalidateQueries) prevents.
Instead of just showing what the code does, this guide explains why each line exists, using scenarios simple enough that the reasoning sticks. Once you understand the "why," the code stops looking like magic.
Here's the mental model for the whole stack, top to bottom:
config/axios.ts- the delivery person: one shared HTTP clientapp/providers/ReactQueryProvider.tsx- the warehouse assistant: caches and syncs dataapp/api/v1/.../route.ts- the store itself: the real data, behind the counteractions/*.ts- trusted errands that fetch on your behalfservices/*.ts- neat, pre-wrapped receiptshooks/use*.ts- how your screen asks for things
What We Are Explaining
By the end of this post, you'll understand exactly what happens in these files:
config/
axios.ts
app/
providers/
ReactQueryProvider.tsx
layout.tsx
app/api/v1/students/route.ts
actions/
students.ts
services/
students.ts
hooks/
useStudents.tsWhat each one is for:
config/axios.ts- one shared Axios instance used everywhereapp/providers/ReactQueryProvider.tsx- the QueryClient, its settings, and the providerapp/layout.tsx- where the provider is mounted for the whole appapp/api/v1/students/route.ts- a real API endpoint (the "store")actions/students.ts- server actions that call the API for youservices/students.ts- typed helpers that wrap those actionshooks/useStudents.ts- the React Query hooks your UI actually uses
And why each individual line is there - not just "what it does," but "what breaks if you remove it."
Before You Start: Installation
Everything below assumes a Next.js 15+ App Router project with TypeScript. If you already have one, skip to Step 2.
Which command do I use? Pick one package manager and stay with it. If you're not sure,
npmcomes with Node.js and works everywhere. The commands below show all three side by side, so copy only the line for your package manager.You'll also see three "runner" commands:
npx(npm),pnpm dlx(pnpm) andbunx(bun). They all do the same thing: run a tool without installing it permanently.
Step 1: Create a Next.js Project (skip if you have one)
# npx
npx create-next-app@latest my-school-app
# pnpm
pnpm create next-app@latest my-school-app
# bun
bun create next-app@latest my-school-appWhen the setup asks questions, choose TypeScript, Tailwind CSS, App Router and the @/* import alias. This guide uses the @/ alias in every import (for example @/config/axios).
Then move into the project:
cd my-school-appStep 2: Install Axios and React Query
These are the three packages the whole guide is built on:
axios- the delivery person that makes HTTP requests@tanstack/react-query- the assistant with the notepad (caching and syncing)@tanstack/react-query-devtools- the inspector panel that lets you see the cache while developing
# npm
npm install axios @tanstack/react-query @tanstack/react-query-devtools
# pnpm
pnpm add axios @tanstack/react-query @tanstack/react-query-devtools
# bun
bun add axios @tanstack/react-query @tanstack/react-query-devtoolsReal-life example: Think of building a house.
axiosis the delivery truck,@tanstack/react-queryis the storekeeper who remembers what's already on site, andreact-query-devtoolsis the clipboard he lets you look at. You don't need the clipboard to build the house, but you'll be very glad to have it the first time something goes missing.
Step 3 (Optional): Toast Notifications
Real apps tell the user "Student added" or "Something went wrong." I use sonner through shadcn/ui, which is also where the <Toaster richColors /> in the layout comes from.
# npx
npx shadcn@latest init
npx shadcn@latest add sonner
# pnpm
pnpm dlx shadcn@latest init
pnpm dlx shadcn@latest add sonner
# bun
bunx --bun shadcn@latest init
bunx --bun shadcn@latest add sonnerIf you already ran shadcn init in this project, run only the add sonner line.
Step 4 (Optional): The API Route Dependencies
Part 4 shows a real API route that uses Prisma (database), Redis (cache) and Better Auth (login). Skip this step if your API already lives somewhere else, or if you're only following along to learn the frontend half.
# npm
npm install @prisma/client ioredis better-auth
npm install -D prisma
# pnpm
pnpm add @prisma/client ioredis better-auth
pnpm add -D prisma
# bun
bun add @prisma/client ioredis better-auth
bun add -d prismaThen create the Prisma setup files and push your schema to the database:
# npx
npx prisma init
npx prisma db push
# pnpm
pnpm dlx prisma init
pnpm dlx prisma db push
# bun
bunx prisma init
bunx prisma db pushPrisma's setup files change a little between major versions, so if
prisma initgenerates something different from what you expect, follow the Prisma docs for your version.
Step 5: Check That It Worked
Open package.json and confirm you see these under dependencies:
{
"dependencies": {
"axios": "...",
"@tanstack/react-query": "...",
"@tanstack/react-query-devtools": "..."
}
}Then start the dev server:
# npm
npm run dev
# pnpm
pnpm dev
# bun
bun devOpen http://localhost:3000. If the default Next.js page loads without red errors, you're ready.
The Big Picture Scenario
Imagine your app needs information that lives far away. Say, a school that keeps all the student records in a big office building downtown - that's your database/API. Your users keep walking up to you and asking, "what's the list of students?"
If you ran to the downtown office every single time someone asked, you'd be exhausted, and so would the office. That's the problem React Query solves.
Now picture three helpers next to you:
- Axios is your delivery person. You hand Axios a note ("go get the students"), and it knows exactly how to navigate the city, which entrance to use, and how to carry the reply back. Without it, you'd have to write the travel instructions from scratch every single time.
- React Query is your personal assistant with a notepad. The first time someone asks for the students, you send Axios downtown, get the answer, and write it on the notepad. The second time someone asks, the assistant just reads the notepad โ instant. If the assistant thinks the notepad might be out of date, it quietly sends Axios to re-check in the background while still showing the old answer, so the user never stares at a blank screen.
- The server action is the trusted errand boy - someone the downtown office actually trusts to knock on its door. Your browser-facing code never talks to the office directly; it sends the errand boy, who brings back a neatly signed receipt.
The rest of this guide explains each of those helpers, one file at a time, so you can reproduce this setup in your own app.
Real-life version: Think of a restaurant. The customer (your screen) never walks into the kitchen. The waiter (server action) takes the order. The kitchen (your API) cooks it. The receipt printer (service) puts the result in a neat format. And the manager with the clipboard (React Query) remembers that table 4 already ordered tea, so he doesn't send the waiter back to the kitchen for the same order twice.
Part 1: config/axios.ts - The Delivery Person
Here's the full file first, so you can see the whole picture. Then we'll go through it line by line.
// config/axios.ts
import axios from "axios";
const serverBaseUrl =
process.env.NEXT_PUBLIC_APP_URL ||
process.env.BETTER_AUTH_URL ||
"http://localhost:3000";
const baseAPI = axios.create({
baseURL:
typeof window === "undefined" ? `${serverBaseUrl}/api/v1` : "/api/v1",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
},
});
export { baseAPI };If you're using environment variables, add them to .env.local in the project root:
NEXT_PUBLIC_APP_URL=http://localhost:3000The Import
import axios from "axios";Scenario: Your app speaks JavaScript, but the outside world speaks raw HTTP. axios is the toolkit that knows how to open an HTTP request, carry headers, and translate the response back into a plain JavaScript object. Everything else in this file builds on top of this one import.
Real-life example: It's like needing to send money. You could walk to a bank in person every time, fill out the forms by hand and wait in line. Or you use mobile money, which already knows how to do all that. Axios is the mobile money of HTTP.
The Server Base URL
const serverBaseUrl =
process.env.NEXT_PUBLIC_APP_URL ||
process.env.BETTER_AUTH_URL ||
"http://localhost:3000";Scenario: When your app is running, it has a front-door address - http://localhost:3000 in development, or your deployed URL in production. This line picks that address, with a couple of fallbacks: NEXT_PUBLIC_APP_URL if it exists, otherwise the auth URL, otherwise a local default. It's a safety net so the server side of your app always knows where it lives when it needs to call its own API.
Real-life example: You're building the school app on your laptop (
localhost:3000). Next month it goes live atmyschool.com. If the address was typed directly inside 40 different files, you'd have to hunt through all 40 to change it. With one environment variable, you change one line and the whole app moves.
The Shared Instance
const baseAPI = axios.create({
baseURL:
typeof window === "undefined" ? `${serverBaseUrl}/api/v1` : "/api/v1",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
},
});Scenario: Instead of telling Axios "go get /api/v1/students" with fresh instructions every time, you create one delivery person (baseAPI) that already knows the neighborhood. axios.create(...) returns a copy of Axios with all these defaults baked in, so every later call stays short and consistent.
Real-life example: A courier company gives each rider a uniform, a bike and a route map on day one. You don't re-explain "wear the jacket, take the bike, here's the city" for every parcel.
baseAPIis a rider who is already fully equipped.
baseURL
baseURL: typeof window === "undefined" ? `${serverBaseUrl}/api/v1` : "/api/v1"Scenario: This is the delivery person remembering the address of the office building. It changes depending on who's sending the request:
typeof window === "undefined"is true on the server (Node.js has nowindow). There, the app must dial out to a full address -http://localhost:3000/api/v1, or the deployed URL - because the server isn't a browser that already knows its own domain.- In the browser (
windowexists), it can use the short relative path/api/v1, and the browser fills in the domain automatically.
Real-life example: If you're standing inside the school compound, you can say "go to the head teacher's office" and everyone knows where. If you're calling from another town, you must give the full address. The browser is already inside the compound. The server is calling from outside.
Content-Type
"Content-Type": "application/json"Scenario: This tells the office: "everything I'm sending you is written in JSON." If you send JSON without declaring it, the office may refuse to read it.
Real-life example: It's the language label on a letter. If you write in Luganda but the envelope doesn't say so, the clerk may not know which translator to call.
Cache-Control
"Cache-Control": "no-store, no-cache, must-revalidate"Scenario: This is two safety warnings in one. It tells the browser and any caching middlemen: "never make a copy of this reply and reuse it" (no-store), and even if a copy exists somewhere, "always go back to the office to double-check before using it" (no-cache, must-revalidate). You're sending live data requests; an old cached copy could show students who were deleted long ago.
Real-life example: A teacher takes attendance at 8:00am and a student is marked absent. At 8:30 the student arrives and is marked present. If the head teacher's screen still shows the 8:00 copy, he'll call the parents about an "absent" child who is sitting in class. Cache headers stop old copies from being reused.
Pragma
"Pragma": "no-cache"Scenario: An older, legacy version of the same warning - some very old proxies only understand Pragma. It's harmless to include and catches those edge cases.
The Export
export { baseAPI };Scenario: One delivery person, shared by the whole app. Every file that needs to talk to the API imports this same instance, so the settings are defined once and never duplicated.
Part 2: app/providers/ReactQueryProvider.tsx - The Assistant's Cage
Here is the full file:
// app/providers/ReactQueryProvider.tsx
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useState } from "react";
export default function ReactQueryProvider({
children,
}: {
children: React.ReactNode;
}) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 15 * 60 * 1000, // 15 minutes
gcTime: 30 * 60 * 1000, // 30 minutes
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}Why "use client"?
"use client";Scenario: React Query keeps its entire cache inside the browser (client-side), so this file must be a Client Component. The "use client" directive tells Next.js not to try rendering this component on the server.
Real-life example: The notepad lives on your desk, not in the head office. Each user's browser has its own notepad, so one user's cached students list is never shown to another user.
The Lazy QueryClient
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 15 * 60 * 1000, // 15 minutes
gcTime: 30 * 60 * 1000, // 30 minutes
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);Scenario: The QueryClient is the assistant's cage โ a single place that holds the notepad (the cache) and the settings that govern it. Everything about this line is deliberate.
useState(() => new QueryClient({ ... }))
Scenario: Notice the arrow function wrapped inside useState(...). This is the "lazy initializer." If you wrote useState(new QueryClient()) โ calling it eagerly โ React would create a brand-new cage on every single re-render, flushing the notepad constantly and wasting memory. By passing a function instead, the QueryClient is created exactly once, on the first render, and then reused. This is one of the most common React Query mistakes, and the fix is this one tiny syntax detail.
Real-life example: Imagine your assistant gets a new notepad every time you walk into the room. You ask "what's on the list?" and he says "I don't know, I just got here." That's what happens without the arrow function: the cache is wiped on every re-render, so nothing is ever remembered.
staleTime
staleTime: 15 * 60 * 1000Scenario: The assistant's rule for "how old is too old before I bother re-asking?" For 15 minutes, data on the notepad is considered fresh โ React Query won't refetch it, no matter how many components ask. 15 * 60 * 1000 is simply 15 minutes in milliseconds (minutes ร 60 seconds ร 1000).
Real-life example: The list of school classes (Primary 1 to Primary 7) almost never changes. There's no reason to ask the server for it every time someone opens a page. A long
staleTimeis perfect for it. In contrast, today's attendance changes every few minutes, so it deserves a shortstaleTime. You choose based on how fast the data really changes.
Real-life example (data costs): Many users browse on mobile data bundles. Every wasted request uses some of their bundle. A sensible
staleTimemeans they download the students list once, not twenty times a day.
gcTime
gcTime: 30 * 60 * 1000Scenario: "gc" stands for garbage collection. This is how long an unused entry stays on the notepad before being thrown away entirely. Notice it's longer than staleTime: staleTime decides "is this answer still trustworthy?" while gcTime decides "is this answer still worth keeping at all?" The rule of thumb is gcTime must be longer than staleTime, or you'll throw away entries before you even consider them outdated - pointless.
Real-life example: Think of milk in a fridge.
staleTimeis "how long it's still good to drink" andgcTimeis "how long until I throw the carton in the bin." You'd never throw the carton away before it expired, that'd be wasteful.
refetchOnWindowFocus
refetchOnWindowFocus: falseScenario: By default, React Query re-fetches everything the moment you click back into the browser tab. In an admin dashboard where data rarely changes second-to-second, that's dozens of wasted requests. false says: "don't re-run errands just because the user switched tabs."
Real-life example: A teacher is marking results, and keeps switching between the school app and WhatsApp. With the default setting, every switch back triggers a full re-download of the data. On slow or expensive internet, that makes the app feel sluggish and burns data for no reason.
retry
retry: 1Scenario: If an errand fails (the office was temporarily closed), the assistant tries once more before giving up and showing the error. This gives transient failures a second chance without hammering a genuinely broken API with ten attempts.
Real-life example: Internet connections drop for a second all the time, especially on mobile networks. One automatic retry quietly fixes most of those blips, so the user never sees an error. But if the server is truly down, you don't want 10 retries piling on and making it worse.
The Provider and Devtools
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);Scenario: <QueryClientProvider client={queryClient}> marks the territory where the assistant operates. Any component under it can call useQuery, useMutation, or useQueryClient and reach this one shared cage. If a component uses these hooks outside the provider, React Query throws a confusing "no QueryClient set" error.
The <ReactQueryDevtools initialIsOpen={false} /> line is your window into the cage, a floating inspector panel (open it in dev with the icon that appears in the corner of your screen) showing every query, its key, its state, and a "refetch" button. Invaluable for debugging. initialIsOpen={false} just means it starts closed, and it only renders in development.
Real-life example: The provider is like the roof of a building. Anything under the roof (inside the provider) is protected and can use the building's facilities. Anything standing outside in the rain can't. The devtools are a glass window in the wall, so you can see what's happening inside.
Part 3: app/layout.tsx - Mounting the Assistant
<ReactQueryProvider>
<ThemeProvider>
<SidebarProvider>{children}</SidebarProvider>
<SessionTimeoutWarning />
<Toaster richColors />
</ThemeProvider>
</ReactQueryProvider>Scenario: The provider has to wrap the whole app - every page and every component - so it goes in the root layout, as close to the top as possible. Note the order: ReactQueryProvider is the outermost, or one of the outermost, wrappers. If any component that calls useQuery sits above it in the tree, that component crashes.
If you just want the minimum version to get started:
// app/layout.tsx
import ReactQueryProvider from "./providers/ReactQueryProvider";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ReactQueryProvider>{children}</ReactQueryProvider>
</body>
</html>
);
}Real-life example: Think of the electricity in a house. You install the main power supply at the whole building's entrance, not in just one room. Then every room (every page) can plug in. If you only wired the kitchen, the bedroom lamp would never turn on.
Part 4: app/api/v1/students/route.ts - The Store Itself
This part needs the Step 4 packages (
@prisma/client,ioredis,better-auth). If your API lives elsewhere, just read this as "the thing on the other end that answers our requests."
export async function GET(request: NextRequest) {
const session = await auth.api.getSession({ headers: request.headers });
if (!session?.user) {
return NextResponse.json(
{ success: false, message: "Unauthorized", ... },
{ status: 401 }
);
}
const cacheKey = studentCacheKeys.bySchool(schoolId ?? "all");
const cached = await getCached<StudentBaseType[]>(cacheKey);
if (cached) {
return NextResponse.json({
success: true,
data: cached,
message: "... (cached)",
...
});
}
const students = await db.student.findMany({ ... });
await setCached(cacheKey, students);
return NextResponse.json({ success: true, data: students, ... });
}Scenario: This is the office building itself. It checks who's knocking (auth), looks at the notepad first (a Redis cache - covered in my cache guide), and only if nothing is cached does it go to the actual filing cabinet (the database). The important detail for this post is its response contract: every route answers with the same JSON shape:
{ success: boolean, data: unknown, message: string, error: string | null, status: number }Both sides of the app (the action caller and your UI) can therefore rely on this shape, which is what makes the next two layers so clean.
Real-life example: Think of a bank. The security guard checks your ID first (auth). Then the teller checks the quick-access drawer for your details (Redis cache). Only if it's not there does she walk to the vault (database). And every customer, no matter the request, gets the same style of receipt back. That consistency is what lets the rest of the app handle replies without guessing.
Part 5: actions/students.ts - The Trusted Errand Boy
Here is the full action file:
// actions/students.ts
"use server";
import axios from "axios";
import { headers } from "next/headers";
import { baseAPI } from "@/config/axios";
async function authHeaders() {
const incomingHeaders = await headers();
return { cookie: incomingHeaders.get("cookie") ?? "" };
}
export async function listStudentsAction() {
try {
const response = await baseAPI.get("/students", {
headers: await authHeaders(),
});
return {
success: response.data.success,
data: response.data.data,
message: response.data.message,
error: response.data.error,
status: response.data.status,
};
} catch (error) {
console.error(error);
// The API answered, but with an error (for example 404: "No school linked")
if (axios.isAxiosError(error) && error.response?.data) {
return {
success: false,
data: [],
message: error.response.data.message ?? "Request failed",
error: error.response.data.error ?? "Request failed",
status: error.response.status,
};
}
// The API never answered (network down, timeout, server crash)
return {
success: false,
data: [],
message: "Failed to fetch students",
error: "Something went wrong. Please try again.",
status: 500,
};
}
}The Directive and Helpers
"use server";
import axios from "axios";
import { baseAPI } from "@/config/axios";
import { headers } from "next/headers";
async function authHeaders() {
const incomingHeaders = await headers();
return { cookie: incomingHeaders.get("cookie") ?? "" };
}Scenario: "use server" marks every exported function as a Server Action - code that always runs on the server, never shipped to the browser. This is the big idea of this pattern: your browser never talks to the API directly; it asks this trusted errand boy to do it.
Real-life example: You don't walk into the bank vault to get your own money. You ask the cashier, who has the keys and the permission. Server actions keep your secrets (API keys, database access) behind the counter, where users' browsers can never reach them.
authHeaders()
Scenario: When the browser started a request, it sent a cookie header that proves "this user is logged in." But the errand boy runs inside a Server Action - a new context - and Axios won't forward those cookies automatically. So headers() re-reads the incoming request's headers, and this helper returns a fresh cookie header to attach to the outgoing API call. Remove this, and every authenticated request comes back 401.
Real-life example: You show your school ID at the main gate, so the guard lets you in. But when you send a friend to collect a book from the library for you, he needs your ID card too, or the librarian says "who are you? I don't know you." The cookie is the ID card, and
authHeaders()hands it to the errand boy.
One Action, End to End
export async function listStudentsAction() {
try {
const response = await baseAPI.get("/students", {
headers: await authHeaders(),
});
// ... return the normalized object
} catch (error) {
// ... return a safe failure object
}
}Scenario: This single action shows the whole errand in motion.
The Request
await baseAPI.get("/students", { headers: await authHeaders() })Scenario: The actual trip. baseAPI (the delivery person) is told the route (/students), with the authenticated cookie attached so the office knows who's asking.
The Returned Object
Scenario: The action normalizes the reply. Whatever the API returns, the action hands your app back a clean, typed shape: success, data, message, error, status. Your UI never has to dig through Axios's response structure.
try / catch
Scenario: If the office is unreachable (server down, timeout), the request throws. Without a try/catch, a thrown error would crash the whole Server Action. Instead, it's caught, logged, and converted into the same response shape with success: false - your UI handles "we tried and it failed" just as elegantly as "it worked."
Real-life example: A parcel can't be delivered because the shop is closed. A good courier doesn't disappear. He comes back and says "shop was closed, delivery failed." Your app can then show a friendly message instead of a blank white screen.
axios.isAxiosError(error)
Scenario: Axios errors aren't plain Errors - they carry error.response?.status and error.response?.data. axios.isAxiosError(error) is a type guard that lets you read those extras safely. A neat trick worth adding to your own version: treat a business 4xx response (like "no school linked") as a normal answer - surface the API's own message to the user - and reserve the generic fallback for genuine network failures.
Real-life example: There are two very different failures. (1) The clerk says "you're not registered at this school." That's a real answer with a real reason, so show it to the user. (2) The phone line is dead and nobody answered at all. That deserves a generic "please try again."
isAxiosErroris how you tell the two apart.
Part 6: services/students.ts โ The Neat Receipts
// services/students.ts
import { listStudentsAction } from "@/actions/students";
export const handleStudent = {
async handleListStudentsService() {
try {
const students = await listStudentsAction();
return {
success: students.success,
data: students.data,
message: students.message,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return { success: false, data: [], message: `Failed: ${errorMessage}` };
}
},
// ...create / update / delete follow the same shape
};Scenario: The service layer is a menu of receipts. It wraps each Server Action in one more try/catch so the calling hook never has to deal with an actual thrown error โ every service method always returns the same typed object. It also logs the real error with console.error(...) while returning a safe, user-friendly message. This is what lets your hooks stay tiny and declarative.
Real-life example: A waiter never walks to your table and says "the cook crashed, I don't know what happened." He always comes back with either your food or a clear message like "sorry, we're out of matooke." The service layer is that waiter: your screen always gets a predictable answer, never a surprise explosion.
Part 7: hooks/useStudents.ts โ How Your Screen Asks for Things
Here's the full hook file:
// hooks/useStudents.ts
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { handleStudent } from "@/services/students";
export function useStudents() {
const queryClient = useQueryClient();
const studentsQuery = useQuery({
queryKey: ["students", "all"],
queryFn: handleStudent.handleListStudentsService,
staleTime: 30000,
gcTime: 3 * 60 * 1000,
});
const createStudentMutation = useMutation({
mutationFn: handleStudent.handleCreateStudentService,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["students"] });
},
onError: (error) => {
console.log(error.message);
},
});
return {
students: studentsQuery.data?.data ?? [],
isLoading: studentsQuery.isLoading,
error:
studentsQuery.error?.message ??
(!studentsQuery.data?.success ? studentsQuery.data?.message : null),
refetch: studentsQuery.refetch,
createStudent: createStudentMutation.mutate,
isCreating: createStudentMutation.isPending,
};
}The Query
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
export function useStudents() {
const queryClient = useQueryClient();
const studentsQuery = useQuery({
queryKey: ["students", "all"],
queryFn: handleStudent.handleListStudentsService,
staleTime: 30000,
gcTime: 3 * 60 * 1000,
});
return {
students: studentsQuery.data?.data ?? [],
isLoading: studentsQuery.isLoading,
error:
studentsQuery.error?.message ??
(!studentsQuery.data?.success ? studentsQuery.data?.message : null),
refetch: studentsQuery.refetch,
};
}Scenario: This is the actual "ask for the students" โ the line your component calls. Everything React Query does (loading state, caching, retrying, syncing) is handled for you; you never write useState + useEffect to fetch data again.
Using it in a component looks like this:
"use client";
import { useStudents } from "@/hooks/useStudents";
export default function StudentsPage() {
const { students, isLoading, error } = useStudents();
if (isLoading) return <p>Loading students...</p>;
if (error) return <p>Something went wrong: {error}</p>;
return (
<ul>
{students.map((student) => (
<li key={student.id}>{student.name}</li>
))}
</ul>
);
}Real-life example: Without React Query, this same page needs a
useStatefor the data, another for loading, another for errors, plus auseEffectto trigger the fetch. Now multiply that by 15 pages. With React Query it's one hook call, and the loading, error, and caching are done for you.
useQueryClient()
Scenario: A handle to the shared cage - the one QueryClient from the provider. You need it later to invalidate queries after a mutation.
queryKey
queryKey: ["students", "all"]Scenario: The label written on the notepad, made of an array. React Query identifies every cached entry by its key: ["students", "all"] for the list, ["students", "one", id] for a single row. The exact same key must be used for the query and for invalidating it, or the assistant can't find what to cross out. Use stable strings; never build keys from random values or objects that change identity on every render.
Real-life example: A filing cabinet with labelled drawers: "Students / All", "Students / One / 42", "Teachers / All". If you file a folder under "Students / All" but later look for it under "students-list", you'll never find it. Keys are the labels on the drawers, so keep them consistent.
queryFn
queryFn: handleStudent.handleListStudentsServiceScenario: The function the assistant runs when it actually needs to go get data. Here it's the service from Part 6 โ a promise that resolves to the normalized response object.
staleTime and gcTime (overridden per query)
staleTime: 30000
gcTime: 3 * 60 * 1000Scenario: These override the provider defaults for this query only. The list is allowed to be re-considered fresh after just 30 seconds (data changes more often here), but the assistant keeps it around for 3 minutes.
Real-life example: The provider says "most things in this school app stay fresh for 15 minutes." But the students list changes more often during registration week, so for this one list we say "re-check after 30 seconds." Global defaults for the general rule, per-query overrides for the exceptions.
students
students: studentsQuery.data?.data ?? []Scenario: While the query hasn't finished, data is undefined. ?. and ?? [] convert that into a safe empty array, so the component can render .map(...) immediately without crashing.
Real-life example: Walking into a class before the register arrives. You don't say "there's no register, everything is broken." You treat it as an empty list for now, and update when it shows up. The
?? []is that sensible default.
isLoading
Scenario: The assistant's "hold on, I'm still checking" flag. The component can show a spinner while it's true. No manual state to manage.
error
Scenario: Slightly clever: errors can come from two places - a thrown network error (query.error) or a business error the API returned inside the response object (data.success === false with a message). This line prioritizes the thrown one, then falls back to the API's message. Either way, the component gets a plain string.
refetch
Scenario: A manual "go check again right now" button the component can trigger - for example, after a search or a pull-to-refresh.
Real-life example: The little refresh button on a mobile money app that lets you re-check your balance, even though the app already shows one.
The Mutations
const createStudentMutation = useMutation({
mutationFn: handleStudent.handleCreateStudentService,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["students"] });
},
onError: (error) => {
console.log(error.message);
},
});Scenario: Reading data is a query; changing data is a mutation - create, update, delete. They're separate tools on purpose.
mutationFn
Scenario: The errand that performs the change - again, a service method that resolves to an answer.
onSuccess and invalidateQueries
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["students"] });
}Scenario: This is the single most important line in the whole stack. After you create a student, the notepad still holds the old list, without the new student. invalidateQueries crosses that entry out and tells the assistant to refetch it. Notice the key here is ["students"] - a partial match - which invalidates both ["students", "all"] and ["students", "one", ...] in one call. Forget this line, and your UI keeps showing stale data even though the database just changed.
Real-life example (the registrar story again): She saves "Aisha Nakato," the database is updated, but the old list is still on screen. Without
invalidateQueries, she sees no Aisha, assumes it failed, and registers her twice. WithinvalidateQueries, the moment the save succeeds the list quietly refreshes, Aisha appears, and the registrar moves on to the next student.
onError
Scenario: What to do when the mutation fails - log it, show a toast, whatever fits your app.
If you installed sonner in Step 3, you can show a friendly message instead of only logging it:
import { toast } from "sonner";
const createStudentMutation = useMutation({
mutationFn: handleStudent.handleCreateStudentService,
onSuccess: () => {
toast.success("Student added successfully");
queryClient.invalidateQueries({ queryKey: ["students"] });
},
onError: (error) => {
toast.error("Failed to add student", { description: error.message });
},
});Real-life example: When you send money and it fails, the mobile money app doesn't stay silent. It says "transaction failed, you have not been charged." Users trust apps that say what happened.
Returned Mutation Helpers
return {
createStudent: createStudentMutation.mutate,
isCreating: createStudentMutation.isPending,
// ...
};Scenario: The hook doesn't run mutations automatically - it hands your component a mutate function to call (for example, from a form's submit handler) and an isPending flag for disabling the button while it runs. This keeps your components looking like forms, not networking code.
Real-life example: The "Pay" button on a checkout page that greys out and says "Processing..." after you click it. That stops you from tapping it five times and paying five times.
isPendingis the flag that makes that possible.
The Dependent Query
export function useStudent(id: string) {
const studentQuery = useQuery({
queryKey: ["students", "one", id],
queryFn: () => handleStudent.handleGetStudentService(id),
enabled: !!id, // don't run until we actually have an id
});
return {
student: studentQuery.data?.data ?? null,
isLoading: studentQuery.isLoading,
};
}Scenario: On a detail page you often don't have the id until the parent loads. enabled: !!id means "if there's no id yet, don't even start the errand" - otherwise React Query would fire a request using undefined and cache a bogus entry. Once id arrives, the query automatically runs.
Real-life example: You can't ask the librarian for "the book with number ___" before you've found the number in the catalogue. You wait until you have it.
enabled: !!idis you waiting for the catalogue number before walking to the shelf.
Putting Everything Together
Here's the full flow, in order, the next time your user lands on the students page:
<StudentsPage />callsuseStudents().- Inside the hook,
useQuery({ queryKey: ["students", "all"], ... })asks React Query: "is this on your notepad, and still fresh?" - React Query says "yes, fresh" โ return the cached array instantly. No network call, no loading spinner, no trip to the office.
- React Query says "no / stale" โ it runs
queryFn, which callshandleStudent.handleListStudentsService(), which callslistStudentsAction(). - The server action (
actions/students.ts) attaches the user's cookie and sendsbaseAPI.get("/students", ...). - The Axios instance (
config/axios.ts) carries the request to/api/v1/students- full URL on the server, relative in the browser. - The API route checks auth, checks the Redis cache, hits the database if needed, and answers with the standard
{ success, data, message, error, status }envelope. - The response walks back up through the action โ service โ hook, where React Query writes it to the notepad, marks it fresh for
staleTime, and hands your componentisLoading: falseplusdata. - Later, someone creates a student via
createStudentMutation.mutate(...). On success,invalidateQueries({ queryKey: ["students"] })crosses out the old list, and the next read refetches - so your screen never shows a form that saved but a list that forgot.
That's it. Every layer has one job, and the data travels a single, predictable path.
Why Is React Query So Important in an App?
If you only take one thing from this guide, take this. Without React Query, every screen that shows server data has to hand-roll the same four things:
- Loading state -
const [loading, setLoading] = useState(true)before every fetch - Error handling -
try/catcheverywhere, with no standard shape - Caching and deduplication - two components asking for the same "students" fire two requests
- Syncing โ after a mutation, you manually call
setStateorwindow.location.reload()to "refetch"
React Query takes all four and makes them automatic and consistent:
- It reads the cache first, network second. The notepad model - fetch once, serve many - is why your app feels instant and stops hammering your API with identical requests.
- It gives you loading/error/"data is here" as plain flags.
isLoading,isError,isPending,data,error- nouseEffectjuggling, no duplicated spinner logic across pages. - It keeps the UI truthful with background refetches.
staleTimeplusrefetchOnMount/refetchOnWindowFocusmean data refreshes quietly in the background; users see the latest information without a full-screen spinner. - It makes "change data, then refresh the screen" a one-liner.
invalidateQueriesandsetQueryDataturn messy post-mutation refresh logic into declarative intent - solving the single most common source of "my list is stale" bugs. - It deduplicates and retries for you. Two components on the same page asking for the same key share one request, and transient failures retry instead of showing a scary error.
Real-life example (one screen, three widgets): A school dashboard has a sidebar showing "Students: 320", a table listing all students, and a chart of enrollment. All three need the students list. Without React Query that's three separate requests to the server. With React Query they all ask for
["students", "all"], so there's one request and all three read the same notepad.
The takeaway: React Query isn't a "fetching library" - it's a server-state manager. Local state (theme, modals) stays in React; server state (students, posts, scores) lives in the cage, and your components just ask.
Common Errors and Fixes
"Module not found: Can't resolve '@tanstack/react-query'" (or axios)
You haven't installed the package, or you installed it in a different folder. Go back to Step 2, run the install command for your package manager inside the project folder (the one containing package.json), then restart the dev server. If you use Bun or pnpm, make sure you're not mixing it with a leftover package-lock.json from npm.
"Cannot find module '@tanstack/react-query-devtools'"
Devtools are a separate package. Install it with the same command as in Step 2, or remove the <ReactQueryDevtools /> line if you don't want them.
"No QueryClient Set" Error
You'll see: No QueryClient set, use QueryClientProvider to set one
Your component calls useQuery but isn't inside <QueryClientProvider>. Mount ReactQueryProvider high โ in the root layout โ and above every component that uses these hooks.
The List Never Updates After Creating, Editing, or Deleting
The mutation forgot queryClient.invalidateQueries({ queryKey: ["students"] }) in onSuccess. The database changed, but the cache didn't. Always pair a write with an invalidation using a key that overlaps the query โ remember, partial keys catch the whole family.
The QueryClient Re-Creates and My Cache Flushes Constantly
You wrote useState(new QueryClient()) instead of useState(() => new QueryClient()). Use the lazy-initializer form so the client is created exactly once.
Authenticated Server Action Suddenly Returns 401/403
Axios doesn't forward the caller's cookies inside a Server Action. Attach them explicitly with { headers: await authHeaders() }, using headers() from next/headers.
Errors Print as a Generic Error With No Status Code
Use axios.isAxiosError(error) to narrow the type, then read error.response?.status and error.response?.data for the real status and server message.
The Detail Page Fires a Pointless Request Before the ID Arrives
The query isn't guarded โ add enabled: !!id so React Query waits for a real id.
Data Looks Old Forever and Never Refetches
Check staleTime and refetchOnWindowFocus. A long staleTime is a valid choice, but you'll need to refetch manually via refetch() or a mutation, and if refetchOnWindowFocus is false, background refresh won't happen when the user returns to the tab.
Two Tabs or Screens Show Inconsistent Data
They're probably using different query keys for the same data, so the assistant treats them as separate notepad entries. Standardize keys โ for example, a small keys object per resource.
Final Checklist
-
axios,@tanstack/react-queryand@tanstack/react-query-devtoolsinstalled with your package manager (npm, pnpm or bun) - One Axios instance in
config/axios.ts, withbaseURLswitching for server vs. client and cache-busting headers -
QueryClientcreated lazily withuseState(() => new QueryClient({ ... })) -
gcTimeis longer thanstaleTime -
ReactQueryProvidermounted in the root layout, above all components that use the hooks - Every server action exports the same response shape:
{ success, data, message, error, status } - Server actions forward the caller's cookie with
authHeaders() - Every resource has a stable
queryKey(list, detail, etc.) reused consistently - Every mutation's
onSuccesscallsinvalidateQuerieswith an overlapping key - Dependent queries use
enabled: !!idso they don't fire before their input exists -
isAxiosErroris used before readingerror.responsedetails
Conclusion
The clean mental model:
config/axios.tsโ one delivery person, pre-configured routesReactQueryProvider.tsxโ one assistant's cage, with sane defaults- API route โ the real store, behind auth and cache
actions/*โ trusted errands that speak for the browserservices/*โ neat typed receipts, never throwhooks/use*โ screens just ask; the assistant handles the errandsqueryKeyโ the notepad label, used for both reading and invalidatingonSuccess+invalidateQueriesโ the exact moment stale data gets corrected
Once you see it as an assistant with a notepad, a delivery person who knows the route, and a trusted errand boy, none of this code is mysterious anymore. Every line handles one very specific, very human problem: make the first request real, make every repeated request fast, and make sure the cache is never lying.
Resources
- TanStack Query โ Overview
- TanStack Query โ Installation
- TanStack Query โ useQuery reference
- TanStack Query โ useMutation reference
- Axios โ Getting started
- Integrating React Query with Server Actions in Next.js 15 โ CodeMint
- React Query, Modern Modal Forms and Reusable Custom Data table โ CodeMint
- Next.js โ Server Actions and Mutations
- Next.js โ headers() API reference
- shadcn/ui โ Sonner