zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.

Made with by Zahid
views
zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.
Made with by Zahid
views
TanStack Query (formerly React Query) simplifies data fetching, caching, and revalidation in React apps — including Next.js.
🔗 Official Docs: https://tanstack.com/query/latest
Install both runtime and dev dependencies:
1npm install @tanstack/react-query
2npm install -D @tanstack/eslint-plugin-query
Create a file like tanstack-provider.tsx inside your project:
1// app/tanstack-provider.tsx
2"use client";
3import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
4import { useState } from "react";
5
6interface TanStackProviderProps {
7 children: React.ReactNode;
8}
9
10export const TanStackProvider = ({ children }: TanStackProviderProps) => {
11 const [queryClient] = useState(() => new QueryClient());
12 return (
13 <QueryClientProvider client={queryClient}>
14 {children}
15 </QueryClientProvider>
16 );
17};
In layout.tsx or app.tsx:
1// app/layout.tsx or app/page.tsx
2import { TanStackProvider } from "./tanstack-provider";
3
4export default function RootLayout({ children }: { children: React.ReactNode }) {
5 return (
6 <html lang="en">
7 <body>
8 <TanStackProvider>{children}</TanStackProvider>
9 </body>
10 </html>
11 );
12}
1"use client";
2import {
3 useQuery,
4 useMutation,
5 useQueryClient,
6} from "@tanstack/react-query";
7
8const getTodos = async () => {
9 const res = await fetch("/api/todos");
10 return res.json();
11};
12
13const postTodo = async (todo: { id: number; title: string }) => {
14 const res = await fetch("/api/todos", {
15 method: "POST",
16 body: JSON.stringify(todo),
17 headers: { "Content-Type": "application/json" },
18 });
19 return res.json();
20};
21
22export default function Todos() {
23 const queryClient = useQueryClient();
24
25 const { data } = useQuery({
26 queryKey: ["todos"],
27 queryFn: getTodos,
28 });
29
30 const mutation = useMutation({
31 mutationFn: postTodo,
32 onSuccess: () => {
33 queryClient.invalidateQueries({ queryKey: ["todos"] });
34 },
35 });
36
37 return (
38 <div>
39 <ul>
40 {data?.map((todo: any) => (
41 <li key={todo.id}>{todo.title}</li>
42 ))}
43 </ul>
44 <button
45 onClick={() => {
46 mutation.mutate({
47 id: Date.now(),
48 title: "Do Laundry",
49 });
50 }}
51 >
52 Add Todo
53 </button>
54 </div>
55 );
56}
You can use:
1invalidateQueries({ queryKey })
1refetchInterval
1refetchOnWindowFocus: true
You're now ready to use useQuery, useMutation , and more anywhere in your Next.js client components. Happy querying!
Tech Stack: Next.js, TanStack Query