Lesson 7 of 11 · 13 min · Building apps

Calling REST APIs: effects, loading states and TanStack Query

Covers: React 19 with TanStack Query v5 and TypeScript. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Fetch data in a component with useEffect, cleanly and without race conditions
  • Model loading, error, empty and success states
  • Send data with POST, PUT and DELETE and refresh the screen
  • Use TanStack Query for caching, retries and background refresh
  • Know when effects are the wrong tool

In simple words

Real apps show data that lives on a server: a list of courses, a user's orders. A component cannot get it while it is being drawn, so it asks after the screen first appears, shows a "loading" message, and then shows the data or an error. Doing this by hand is easy to get subtly wrong (old answers overwriting new ones, no retries, no caching), so most teams use a library that does it properly.

Words to know

  • Effect: code React runs after rendering, to synchronise with something outside React, such as the network.
  • Side effect: anything that reaches outside the component, such as a request or a timer.
  • Cache: stored results that are reused instead of asking the server again.
  • Mutation: a request that changes data on the server.

The basic pattern: useEffect

import { useEffect, useState } from "react";

type Course = { id: number; title: string };
type State =
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "success"; data: Course[] };

function CourseList() {
  const [state, setState] = useState<State>({ status: "loading" });

  useEffect(() => {
    const controller = new AbortController();
    setState({ status: "loading" });

    fetch("/api/courses", { signal: controller.signal })
      .then((response) => {
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json() as Promise<Course[]>;
      })
      .then((data) => setState({ status: "success", data }))
      .catch((error) => {
        if (error.name === "AbortError") return;          // the effect was cleaned up: ignore
        setState({ status: "error", message: "Could not load courses." });
      });

    return () => controller.abort();                      // cleanup: cancel on unmount or when deps change
  }, []);                                                 // [] = run once after the first render

  if (state.status === "loading") return <p role="status">Loading...</p>;
  if (state.status === "error") return <p role="alert">{state.message}</p>;
  if (state.data.length === 0) return <p>No courses yet.</p>;
  return <ul>{state.data.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}

What each part does:

  • useEffect(setup, dependencies) runs after the component renders. The dependency array lists the reactive values the effect uses (props, state); the effect re-runs when any of them changes; [] means once on mount.
  • The cleanup function runs before the next run and on unmount: here it aborts the request, so a slow old response cannot update the state of an unmounted component or overwrite a newer result (a race).
  • In StrictMode (development), React runs mount, cleanup and mount again to check your cleanup works, so you will see two requests in development. That is intentional; with correct cleanup, behaviour is the same.
  • Model the result as one status value (a discriminated union), not separate loading, error and data booleans.
  • Handle empty results as a normal state.

With parameters

function Orders({ status }: { status: string }) {
  const [orders, setOrders] = useState<Order[]>([]);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/orders?status=${encodeURIComponent(status)}`, { signal: controller.signal })
      .then((r) => r.json())
      .then(setOrders)
      .catch(() => {});
    return () => controller.abort();                      // a new status cancels the previous request
  }, [status]);                                           // re-run when status changes
  // ...
}

List every value the effect reads in the dependency array; the lint rule react-hooks/exhaustive-deps helps. Do not silence it: a missing dependency means a stale closure (the effect uses old values).

Sending data

Mutations usually happen in event handlers, not effects:

async function handleSubmit(event: React.FormEvent) {
  event.preventDefault();
  setSaving(true);
  try {
    const response = await fetch("/api/orders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ customerId, productIds }),
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const created: Order = await response.json();
    setOrders((list) => [...list, created]);              // update the screen
  } catch {
    setError("Could not save. Please try again.");
  } finally {
    setSaving(false);
  }
}

Disable the button while saving (prevent double submits), show errors, and update or refetch the list afterwards. For immediate feedback, optimistic updates show the change first and roll back if the server fails (React 19's useOptimistic and TanStack Query both support this).

You might not need an effect

Effects are for synchronising with external systems (network, timers, subscriptions, the DOM). Do not use them for:

  • Transforming data for display (filter, sort, totals): compute during render.
  • Responding to a user action: do it in the event handler.
  • Resetting state when a prop changes: use a key.
  • Chaining state updates (an effect that sets state that triggers another effect): restructure.

Data fetching in effects has real weaknesses: no cache (the same request repeats in every component and on every visit), request waterfalls (a child fetches only after its parent finishes), no automatic retry, refresh on focus, deduplication, or pagination support, and a lot of boilerplate. The React docs recommend using a framework's data loading, or a library such as TanStack Query or SWR, rather than writing effects by hand. (React 19's use hook with Suspense also reads promises during render, typically with a framework's help.)

TanStack Query

npm install @tanstack/react-query

Set it up once:

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

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 30_000, retry: 2 } },
});

createRoot(document.getElementById("root")!).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Read data with useQuery:

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

async function getCourses(signal: AbortSignal): Promise<Course[]> {
  const response = await fetch("/api/courses", { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

function CourseList() {
  const { data, isPending, isError, error, refetch } = useQuery({
    queryKey: ["courses"],                          // the cache key
    queryFn: ({ signal }) => getCourses(signal),    // cancellation comes for free
  });

  if (isPending) return <p role="status">Loading...</p>;
  if (isError) return (
    <div role="alert">
      <p>{error.message}</p>
      <button type="button" onClick={() => refetch()}>Try again</button>
    </div>
  );
  return <ul>{data.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}

What you get without extra code:

  • Caching and deduplication: ten components calling useQuery({ queryKey: ["courses"] }) trigger one request and share the result.
  • Stale-while-revalidate: cached data shows instantly and is refreshed in the background; staleTime controls how long data counts as fresh.
  • Automatic retries, refetch on window focus and reconnect, polling (refetchInterval), pagination and infinite scroll (useInfiniteQuery), dependent queries (enabled), prefetching.
  • Statuses: isPending, isError, isSuccess, isFetching (background refresh), isRefetching.

Query keys identify data and include the parameters: ["orders", { status }]; when status changes the key changes and a new query runs.

Changing data with useMutation, then telling the cache what is out of date:

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

function AddCourse() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (course: { title: string }) =>
      fetch("/api/courses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(course),
      }).then((r) => { if (!r.ok) throw new Error("save failed"); return r.json(); }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["courses"] }),   // refetch the list
  });

  return (
    <button type="button" disabled={mutation.isPending} onClick={() => mutation.mutate({ title: "React" })}>
      {mutation.isPending ? "Saving..." : "Add course"}
    </button>
  );
}

invalidateQueries marks cached data stale and refetches active queries, keeping lists in sync after changes. TanStack Query separates server state (data owned by the server, cached copies) from client state (UI state in useState), which removes most need for global stores.

An API helper and typed errors

Centralise requests: base URL, JSON handling, ok checks, authentication headers, and typed errors (the fetch lesson's api() helper):

export class ApiError extends Error {
  constructor(public status: number, message: string) { super(message); }
}
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(`/api${path}`, { credentials: "include", ...init });
  if (!response.ok) throw new ApiError(response.status, `Request failed: ${response.status}`);
  return response.status === 204 ? (undefined as T) : response.json();
}
  • Handle 401 globally (redirect to login or refresh the token) and 403/404 meaningfully.
  • Validate response shapes with Zod when the data matters.
  • Never put secrets in front-end code. Keep API URLs in environment variables (import.meta.env.VITE_API_URL in Vite; every VITE_ variable is public).
  • In development, use a proxy (server.proxy in vite.config.ts) to avoid CORS during development, and configure CORS properly on the real API (the CORS lesson).

UX of data loading

  • Show a skeleton or spinner after a short delay (avoid flashes for fast responses).
  • Keep previous data visible while refetching (placeholderData: keepPreviousData for paginated lists).
  • Offer retry, show friendly errors, and handle offline gracefully.
  • Paginate or virtualise large lists; debounce search inputs (the debounce lessons).
  • Announce changes to assistive technology (role="status" and role="alert").

Common mistakes

  • Forgetting the cleanup (race conditions, setting state after unmount).
  • Missing or wrong dependencies in useEffect.
  • Fetching in the render body (an infinite loop of renders).
  • An async function passed directly to useEffect (the effect cannot return a promise; define an inner async function).
  • Using effects for derived data or for reacting to clicks.
  • Hand-rolling caching and retries that a library provides.
  • No loading, error or empty states.
  • Putting secrets in VITE_ variables.

Try it yourself

  1. Fetch a list in useEffect with AbortController, and reproduce a race by switching a filter quickly with a slow network.
  2. Add loading, error (with retry) and empty states.
  3. Replace the effect with useQuery and compare the amount of code and behaviour (open the same page in two components).
  4. Add a "create" button with useMutation that invalidates the list.
  5. Turn on network throttling and "Offline" in DevTools to test the states.

Check yourself

Why do you return a cleanup function from a fetching effect?

To cancel the request (or ignore its result) when the component unmounts or the dependencies change, preventing race conditions and updates on unmounted components.

What does the dependency array of useEffect control?

When the effect re-runs: after the first render and whenever any listed value changes; an empty array means once.

Name three things TanStack Query provides that a hand-written effect does not.

Caching with deduplication, automatic retries and background refetching (and pagination, dependent queries, optimistic updates).

Where should a POST that saves a form be triggered?

In an event handler (such as submit), not in an effect, because it responds to a user action.

Interview questions

How do you fetch data in React?

In plain React with useEffect (with cleanup and dependency array), storing status, data and error in state; in practice with a library such as TanStack Query or SWR, or a framework's loaders, which add caching, deduplication, retries and better loading states.

What is a race condition in data fetching and how do you prevent it?

A slow earlier response arriving after a newer one and overwriting it; prevent it by aborting the previous request in the effect cleanup (AbortController) or ignoring stale responses, or by using a query library.

Why does my effect run twice in development?

StrictMode intentionally mounts, unmounts and remounts components to reveal effects without proper cleanup; production runs it once.

Summary

  • Fetch in useEffect with an AbortController cleanup and a status union; mutate in event handlers.
  • Do not use effects for derived data, user actions or state resets.
  • TanStack Query adds caching, retries, refetching and mutations with invalidateQueries.
  • Centralise API calls, validate data, handle auth and errors, and never put secrets in the front end.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.