Skip to article content
FrontendXLesson 37 / 40

Data Fetching and Client Caches

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

advanced · about 60 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Interview

What you will be able to do

#
  • Fetch data in an effect with cancellation to avoid races.
  • Cache and deduplicate requests across components.
  • Explain stale-while-revalidate and cache invalidation.

Overview

#

Fetching in an effect

A common pattern fetches in an effect and stores the result in state. The effect must handle the case where the component unmounts or the input changes before the request resolves, or a slow earlier response can overwrite a newer one. Use an AbortController or an ignore flag.

snippet.tsx
useEffect(() => {
  const controller = new AbortController();
  fetch(url, { signal: controller.signal })
    .then((r) => r.json())
    .then(setData)
    .catch((e) => { if (e.name !== 'AbortError') setError(e); });
  return () => controller.abort();
}, [url]);

The race condition

Without cancellation, two requests can resolve out of order and the UI shows the older result. Cancelling on cleanup or ignoring stale responses fixes it.

Caching and deduplication

Fetching the same data in several components causes duplicate requests. A client cache keyed by request stores the result and lets components share it. Deduplication means two components asking for the same key at the same time issue one request.

Stale-while-revalidate

A cache can return the cached value immediately and revalidate in the background. The user sees data instantly, and the cache updates when the fresh response arrives. This is the model behind libraries such as SWR and TanStack Query.

Suspense and use

With a cached promise, a component can read it with use and let a Suspense boundary show the fallback. The promise must be cached, not created during render, or the component suspends forever.

Pitfall: fetching in an effect when a framework can do it

If the app uses server components or a data router, fetch on the server or in the router loader. Client effects are for data that genuinely depends on client state.

Pitfall: cache invalidation

A cache that is never invalidated shows stale data after a mutation. After a write, invalidate or update the affected keys so the next read is fresh.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    The user clicks item A then item B quickly. A's response arrives last. What is shown?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    useEffect(() => {
      fetch(`/api/${id}`).then((r) => r.json()).then(setData);
    }, [id]);
    Choose the best answer
  2. Exercise 2Implement

    Fetch data in an effect and abort the request when the id changes or the component unmounts.

    starter.tsx
    export function Detail({ id }: { id: string }) {
      const [data, setData] = useState<Item | null>(null);
      return <div>{data?.title}</div>;
    }

    Reveal the reference answer
    reference.tsx
    export function Detail({ id }: { id: string }) {
      const [data, setData] = useState<Item | null>(null);
      useEffect(() => {
        const controller = new AbortController();
        fetch(`/api/items/${id}`, { signal: controller.signal })
          .then((r) => r.json())
          .then(setData)
          .catch((e) => { if (e.name !== 'AbortError') console.error(e); });
        return () => controller.abort();
      }, [id]);
      return <div>{data?.title}</div>;
    }

    Authored expected output: Changing id aborts the previous request, so only the latest response updates the UI.

    The cleanup aborts the in-flight request when id changes or the component unmounts. The AbortError is ignored so a normal cancellation is not logged as a failure.

  3. Exercise 3Debug

    Two sibling components fetch the same URL and the network tab shows two requests. Explain and fix.

    starter.tsx
    useEffect(() => { fetch('/api/me').then((r) => r.json()).then(setUser); }, []);

    Reveal the reference answer
    reference.tsx
    // Use a shared cache that deduplicates by key:
    const cache = new Map<string, Promise<unknown>>();
    function fetchCached(url: string) {
      if (!cache.has(url)) cache.set(url, fetch(url).then((r) => r.json()));
      return cache.get(url)!;
    }
    
    useEffect(() => { fetchCached('/api/me').then(setUser); }, []);

    Authored expected output: The network tab shows one request shared by both components.

    Each component fetches independently, so both issue requests. A cache keyed by URL stores the in-flight promise, so the second caller reuses it instead of starting a new request.

  4. Exercise 4Interview

    Explain stale-while-revalidate and how you would keep a cache consistent after a mutation.

    starter.tsx
    // cache, revalidate, invalidate on write

    Reveal the reference answer
    reference.tsx
    Stale-while-revalidate serves the cached value immediately so the UI is instant, then revalidates in the background and updates the cache when fresh data arrives. It trades a brief moment of possibly stale data for perceived speed. After a mutation, the cached data for the affected keys is wrong, so you invalidate those keys to force a refetch, or update them optimistically with the new value. The rule is that every write must either invalidate or update the keys it affects, otherwise reads serve stale data.

    Authored expected output: A definition of stale-while-revalidate plus the invalidation or update rule after a write.

    The answer should connect the read strategy to the write strategy, since consistency depends on both.

Common misconceptions

#
  • Fetching in an effect needs no cleanup. Without cancellation, a slow response can overwrite a newer one.
  • Each component should fetch its own data. A shared cache deduplicates and keeps values consistent.
  • A cache never needs invalidation. After a mutation, invalidate or update the affected keys.
  • You can create the promise during render for use. It must be cached or the component suspends repeatedly.

Follow-up practice

#
  • react-server-components
  • react-actions-and-server-functions

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.