Set Up TanStack Query
To display products, we need to fetch data from the DummyJSON API. You might reach for useEffect + useState:
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchProducts()
.then(setProducts)
.catch(setError)
.finally(() => setLoading(false));
}, []);
This works, but it gets tedious fast. Every component that fetches data needs the same boilerplate. And you do not get any of the extra behavior you want: no caching, no automatic refetching, no deduplication if two components request the same data.
TanStack Query (formerly React Query) handles all of this. You give it a fetch function, and it manages loading states, errors, caching, and background refetching for you.
Install TanStack Query
pnpm add @tanstack/react-query
Configure the provider
TanStack Query needs a QueryClient, the object that holds the cache, and a QueryClientProvider that makes it available to the entire app.
Update src/main.tsx:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { createRouter, RouterProvider } from "@tanstack/react-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; // ๐ Import QueryClient and QueryClientProvider
import { routeTree } from "./routeTree.gen";
import "./index.css";
const router = createRouter({ routeTree, basepath: "/shopping-cart" });
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
const queryClient = new QueryClient(); // ๐ Create a query client
createRoot(document.getElementById("root")!).render(
<StrictMode>
{/* ๐ Wrap the router with the query client */}
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</StrictMode>,
);
The QueryClientProvider wraps the entire app so any component can use useQuery.
The basepath should match the base in vite.config.ts for GitHub Pages deployment. If your repository name is not shopping-cart, update both values to match your repository name.
Checkpoint: Commit your progress.
git add .
git commit -m "shopping-cart-03: Set up TanStack Query"
git push