EasyEcosystem📖 Theory Question

What is TanStack Query (React Query) and what does it solve?

💡

Hint

Async state manager for server data — caching, background refetch, stale-while-revalidate, mutations

Full Answer

React Query manages server state with automatic caching, background updates, and synchronization — things you'd have to build manually with useEffect.

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// ─── Query — fetch and cache ──────────────────────────────────────────────────
function UserProfile({ id }) {
  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', id],      // cache key — same key = same cache
    queryFn: () => api.getUser(id),
    staleTime: 5 * 60 * 1000,   // treat as fresh for 5 minutes
    gcTime: 10 * 60 * 1000,     // keep in cache for 10 minutes
  });

  if (isLoading) return ;
  if (error) return ;
  return 

{user.name}

; } // ─── Mutation — update and invalidate ──────────────────────────────────────── function UpdateUser() { const queryClient = useQueryClient(); const mutation = useMutation({ mutationFn: (data) => api.updateUser(data), onSuccess: (data) => { // Invalidate cache → triggers refetch of all user queries queryClient.invalidateQueries({ queryKey: ['user'] }); // OR optimistic update queryClient.setQueryData(['user', data.id], data); }, }); return ( ); }
💡 React Query eliminates ~80% of what people used Redux for — loading states, error states, cached server data, and refetch logic. Use Redux or Zustand only for genuine UI state (modals, sidebars, form wizards).

More Ecosystem Questions

EasyWhat is the difference between Next.js Pages Router and App Router?EasyWhat is Zustand and how does it compare to Context?MediumWhat are the key differences between Vite and Create React App?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint