062
LVL 03 — MID DEVELOPERSESSION 062DAY 62

REACT QUERY

🎫 PIXELCRAFT-049
🔧Refactor | 🟡 Medium | Priority: 🟡 Medium

Every component that fetches data has the same pattern: loading state, error state, data state, useEffect, cleanup. The code is repetitive and error-prone. Introduce TanStack Query (React Query).
CONCEPTS.UNLOCKED
TanStack Query
Data fetching library that handles caching, loading, errors, and refetching automatically. Replace manual useState + useEffect patterns with a declarative API.
📥
useQuery
Fetch and cache data. Give it a key and a function. It returns { data, isLoading, error }. Handles caching, deduplication, background refetching, and stale data.
📤
useMutation
Create, update, delete with optimistic updates. Wraps POST/PUT/DELETE calls with loading state, error handling, and automatic cache invalidation on success.
🔄
Query Invalidation
Refetch when data changes. After a mutation succeeds, invalidate related queries. The gallery automatically refreshes when you upload or delete an image.
📦
Stale-While-Revalidate
Show cached data immediately, update in background. Navigate away and back — gallery loads instantly from cache while fresh data loads behind the scenes.
🧹
No More Boilerplate
30 lines of manual fetching became 5 lines with useQuery. No useState for loading/error/data. No useEffect for fetching. No cleanup. Just declare what you need.
HANDS-ON.TASKS
01
Install & Set Up QueryClient
npm install @tanstack/react-query import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> {/* ... */} </QueryClientProvider> ); }
02
Replace Manual Fetch with useQuery
function Gallery() { const { data: images, isLoading, error } = useQuery({ queryKey: ['images'], queryFn: () => api('/api/images'), }); if (isLoading) return <Spinner />; if (error) return <ErrorMessage message={error.message} />; return ( <div className="grid grid-cols-4 gap-4 p-4"> {images.map(img => <ImageCard key={img._id} image={img} /> )} </div> ); }
Compare: before (30 lines of useState + useEffect + cleanup) vs after (5 lines with useQuery). Same result, fraction of the code.
03
Mutations with Cache Invalidation
function useDeleteImage() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (imageId) => api(`/api/images/${imageId}`, { method: 'DELETE' }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['images'] }); // Refetch gallery }, }); } // Usage in component: const deleteImage = useDeleteImage(); <button onClick={() => deleteImage.mutate(image._id)}> Delete </button>
04
Verify Cache Behavior

Navigate away from gallery and back — data loads instantly from cache. Delete an image — gallery automatically refetches. No manual state management.

05
Close the Ticket
git switch -c refactor/PIXELCRAFT-049-react-query git add src/ git commit -m "Migrate to React Query, remove fetch boilerplate (PIXELCRAFT-049)" git push origin refactor/PIXELCRAFT-049-react-query # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Caching strategies.

Stale-while-revalidate: show cached data immediately (fast), then refetch in the background (fresh).

// The same caching strategy everywhere:

CDNs          → serve cached content,
                 check for updates
Browsers      → cache resources
DNS           → cache IP lookups
CPU L1/L2/L3  → cache recently
                 accessed memory

// Cache invalidation is famously one
// of the two hardest problems in CS
// (the other being naming things).
"Query Lab"
[A]Add optimistic updates to delete: remove the image from the UI immediately, then send the request. If it fails, add it back. Use useMutation's onMutate and onError callbacks.
[B]Add useInfiniteQuery for the gallery: load 20 images at a time, "Load More" button fetches the next page. Integrate with the paginated API from Session 65.
[C]Install React Query DevTools (@tanstack/react-query-devtools). Inspect cache entries, query states, and refetch timing. Understand what's happening under the hood.
REF.MATERIAL
ARTICLE
Tanner Linsley
Official guide: queries, mutations, invalidation, caching strategies, and DevTools. The definitive React Query reference.
REACT QUERYOFFICIALESSENTIAL
VIDEO
Fireship
Ultra-fast overview: why React Query exists, useQuery, useMutation, caching, and stale-while-revalidate.
REACT QUERYQUICK
VIDEO
Web Dev Simplified
Practical walkthrough: setup, useQuery, useMutation, cache invalidation, and pagination. Everything from this session.
REACT QUERYPRACTICAL
ARTICLE
Google
The caching strategy explained: serve stale, revalidate in background. Used by CDNs, browsers, and now your React app.
CACHINGSTRATEGY
ARTICLE
Dominik Dorfmeister
Best practices from a React Query maintainer: query key structure, error handling, optimistic updates, and common pitfalls.
REACT QUERYBEST PRACTICES
// LEAVE EXCITED BECAUSE
30 lines of manual fetching became 5 lines. Caching, loading, error handling, and refetching are all automatic. Navigate away and back — data loads instantly from cache.