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
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?