TanStack Query (React Query)
Definition
TanStack Query is a powerful asynchronous state management library for React. It replaces `useEffect` and `useState` for data fetching by handling caching, background updates, loading states, and error handling out-of-the-box.
Explain Like I'm New
Writing your own `useEffect` fetch logic is like building your own refrigerator to keep food cold. You have to handle power outages, temperature control, and mold. TanStack Query is a smart, enterprise-grade refrigerator you just buy. You tell it "Get me the milk from the store" (fetch), and it automatically fetches it, caches it, keeps it fresh in the background, and gives it to anyone in the house who asks for it instantly.
Real World Example
Instead of using `useEffect` to fetch a user profile, you use `const { data, isLoading } = useQuery({ queryKey: ["user"], queryFn: fetchUser })`. If 5 different components on the screen all call this hook, TanStack Query is smart enough to only make 1 single network request and share the result with all 5.
Common Use Cases
- •Eliminating almost all `useEffect` hooks in a codebase
- •Implementing infinite scrolling or pagination
- •Sharing server data globally without Redux or Context
Interactive Example
/* // Conceptual Example - Requires npm install @tanstack/react-query import { useQuery } from "@tanstack/react-query"; // The actual fetching logic (can be fetch, axios, graphql, etc) const fetchWeather = async () => { const res = await fetch("/api/weather"); return res.json(); }; export default function WeatherWidget() { // React Query handles all the complex state! const { data, isLoading, isError, error } = useQuery({ queryKey: ["weather", "NewYork"], // The unique ID for this data queryFn: fetchWeather, staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes. Don't refetch if asked again. refetchOnWindowFocus: true // Automatically update when user comes back to the tab }); if (isLoading) return <div>Loading weather...</div>; if (isError) return <div>Error: {error.message}</div>; return ( <div> <h3>New York Weather</h3> <p>{data.temp}°F - {data.condition}</p> </div> ); } */ console.log("TanStack Query is widely considered the missing data-fetching library for React.");
Interview Questions
basic
- What is the difference between Server State and Client State?
- Why does React Query make Redux almost obsolete for many apps?
intermediate
- What is a `queryKey` and why is it important?
- What is the difference between `staleTime` and `gcTime` (cacheTime)?
advanced
- How does React Query handle window focus events?
- What is query invalidation?
trick
- Does TanStack Query actually make HTTP requests?