Script Valley
React.js: Complete Course
State Management with Zustand and React QueryLesson 6.3

React Query: fetching and caching server data

TanStack Query setup, QueryClient, QueryClientProvider, useQuery hook, queryKey, queryFn, loading and error states, automatic refetching, staleTime, cacheTime

React Query for Server State

React Query (TanStack Query) manages server state: fetching, caching, synchronizing, and updating. It eliminates the boilerplate of useEffect data fetching and handles loading, error, refetching, and stale data automatically.

npm install @tanstack/react-query

Setup

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Router />
    </QueryClientProvider>
  );
}

useQuery

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

function UserList() {
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('/api/users').then(r => r.json()),
    staleTime: 60 * 1000, // 60 seconds before refetch
  });

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error: {error.message}</p>;

  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

React Query caches by queryKey. Multiple components using the same key share one request. After staleTime elapses, React Query refetches in the background when the window refocuses or the component remounts.

Up next

React Query mutations: creating, updating, and deleting data

Sign in to track progress