React Tutorial 0/120 lessons ~6 min read Lesson 69

    React Query Basics

    React Query Basics covers TanStack Query server state, query keys, invalidation, useQuery versus useMutation, and QueryClient setup.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Course: React — State Management Lesson: 09

    Learning objectives

    Understand server state, configure TanStack Query (formerly commonly called React Query), fetch data with useQuery, perform mutations, and understand query keys.

    What problem does TanStack Query solve?

    Server data has concerns beyond storing a value: freshness, caching, background refetching, retries, request deduplication, invalidation, and synchronization after mutations. TanStack Query is designed to manage this server-state lifecycle.

    Install:

    bash
    npm install @tanstack/react-query

    Configure QueryClient

    javascript
    import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
    const queryClient = new QueryClient();
    function App() {
    return (
    <QueryClientProvider client={queryClient}>
    <Application />
    </QueryClientProvider>
    );
    }

    Create the client outside the component render so it is not recreated on every render.

    Fetch with useQuery

    javascript
    function OrdersPage() {
    const query = useQuery({
    queryKey: ["orders"],
    queryFn: fetchOrders
    });
    if (query.isPending) return <OrdersSkeleton />;
    if (query.isError) return <ErrorPanel error={query.error} />;
    return <OrderTable orders={query.data} />;
    }

    The query key identifies the data. The query function retrieves it. TanStack Query manages the request lifecycle and cache according to its configuration.

    Query keys must describe the data

    If results depend on filters, include those filters in the key:

    javascript
    useQuery({
    queryKey: ["orders", { status, page }],
    queryFn: () => fetchOrders({ status, page })
    });

    A key that omits meaningful inputs can cause different views to share an incorrect cache entry.

    Mutations and invalidation

    javascript
    const queryClient = useQueryClient();
    const mutation = useMutation({
    mutationFn: createOrder,
    onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ["orders"] });
    }
    });

    Invalidation marks matching cached data stale so it can be refetched according to query activity and configuration.

    Server state vs client state

    TanStack Query is not intended to replace every local state variable. Keep modal visibility and temporary form interaction in component state. Keep remote order data in the query cache. This separation gives each category an appropriate lifecycle.

    Common mistakes

    • Using incomplete query keys.
    • Creating a new QueryClient on every render.
    • Putting local UI state into the query cache.
    • Assuming invalidation always means an immediate network request in every situation.
    • Sharing cached data across users or tenants without appropriate key scope and cache lifecycle management.

    Best practices

    Use stable, complete query keys, centralize query defaults, invalidate after successful mutations, handle pending/error/empty states, and clear or isolate user-scoped cache on logout or tenant change.

    Interview questions & answers

    Interview preparation

    5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.

    Beginner

    2
    1. 1What is server state?
      Beginner

      Model answer

      Remote data owned by the backend and synchronized into the client with caching and freshness rules.

    2. 2Difference between useQuery and useMutation?
      Beginner

      Model answer

      useQuery reads/caches server data. useMutation performs create/update/delete operations and can trigger invalidation.

    Intermediate

    2
    1. 3What is the purpose of a query key?
      Intermediate

      Model answer

      It uniquely identifies cached data, including every input that changes the result such as filters, ids, and tenant scope.

    2. 4Why should a QueryClient be created outside a component render?
      Intermediate

      Model answer

      Creating it during render can reset cache on each mount/render cycle; a stable client preserves cached data.

    Advanced

    1
    1. 5What does query invalidation do?
      Advanced

      Model answer

      It marks cached queries stale so they refetch and stay consistent after mutations or external changes.

    Practice

    Build an orders page with status and page filters. Use query keys that include both filters, add an order mutation, and invalidate the order list after creation.

    Ready to mark this lesson complete?Track your journey across the entire course.