Skip to article content
FrontendXLesson 08 / 40

Data Fetching, Suspense and Transitions

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.

intermediate · about 60 minutes · 4 exercises

  • Predict
  • Explain
  • Implement
  • Debug

What you will be able to do

#
  • Fetch data without race conditions using AbortController.
  • Read a promise with the use hook and Suspense.
  • Keep input responsive with useTransition and useDeferredValue.

Overview

#

Race conditions

If two requests are in flight and the slower one resolves last, it overwrites the newer result. Always cancel or ignore stale responses. AbortController is the cleanest approach.

snippet.tsx
useEffect(() => {
  const controller = new AbortController();
  let active = true;
  fetch(url, { signal: controller.signal })
    .then((r) => r.json())
    .then((data) => { if (active) setData(data); })
    .catch((e) => { if (e.name !== "AbortError") throw e; });
  return () => { active = false; controller.abort(); };
}, [url]);

The use hook and Suspense

React 19's use hook reads a promise or a context during render. When used with a promise, the component suspends until the promise resolves, and a Suspense boundary shows a fallback.

snippet.tsx
function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
  const comments = use(commentsPromise);
  return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
}

<Suspense fallback={<p>Loading comments</p>}>
  <Comments commentsPromise={commentsPromise} />
</Suspense>

The promise must be created outside render, or cached, so it is not recreated on every render. use can also read context conditionally, unlike useContext.

Transitions

useTransition marks a state update as non-urgent so React can keep the UI responsive. The returned isPending flag lets you show a subtle indicator while the transition runs.

snippet.tsx
const [isPending, startTransition] = useTransition();

function onChange(e: React.ChangeEvent<HTMLInputElement>) {
  const value = e.target.value;
  setQuery(value); // urgent: keeps the input responsive
  startTransition(() => setFilter(value)); // non-urgent: can lag
}

useDeferredValue is the other side of the same idea: give it a value and it returns a deferred copy that lags behind during heavy renders.

snippet.tsx
const deferredQuery = useDeferredValue(query);
const results = useMemo(() => search(deferredQuery), [deferredQuery]);

Choosing

Use AbortController for correctness in any effect-based fetch. Use use with Suspense when you have a stable promise and want declarative loading. Use transitions and deferred values when a render is expensive and you want to keep typing smooth.

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

    A user types "ab" quickly. Requests for "a" and "ab" are in flight. What is shown if the "a" response arrives last and there is no cancellation?

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

    Implement a useSearch hook that fetches results for a query, cancels the previous request, and ignores stale responses.

    starter.tsx
    export function useSearch(query: string) {
      return [];
    }

    Reveal the reference answer
    reference.tsx
    import { useEffect, useState } from "react";
    
    export function useSearch(query: string) {
      const [results, setResults] = useState<string[]>([]);
      useEffect(() => {
        const controller = new AbortController();
        fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
          .then((r) => r.json())
          .then(setResults)
          .catch((e) => { if (e.name !== "AbortError") throw e; });
        return () => controller.abort();
      }, [query]);
      return results;
    }

    Authored expected output: Only the latest query's results are shown; earlier requests are aborted.

    The effect re-runs when query changes. Cleanup aborts the previous request, so its response never reaches setResults. Ignoring AbortError avoids surfacing a cancelled request as an error.

  3. Exercise 3Debug

    This Suspense example re-fetches on every render and flashes the fallback. Fix the promise handling.

    starter.tsx
    function Comments() {
      const comments = use(fetch("/api/comments").then((r) => r.json()));
      return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
    }

    Reveal the reference answer
    reference.tsx
    function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
      const comments = use(commentsPromise);
      return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
    }

    Authored expected output: The fallback shows once; the promise is stable across renders.

    Creating the promise inside render produces a new promise every render, so the component suspends again and again. Hoisting or caching the promise outside render makes it stable, which is required by the use hook.

  4. Exercise 4Explain

    Explain the difference between useTransition and useDeferredValue and when each is appropriate.

    starter.tsx
    startTransition(() => setFilter(value));
    const deferred = useDeferredValue(value);

    Reveal the reference answer
    reference.tsx
    useTransition wraps a state update you trigger, marking it non-urgent and giving you an isPending flag. useDeferredValue takes a value you already have and returns a lagging copy, so it is useful when you cannot wrap the update, such as when the value comes from props. Both keep urgent updates responsive; choose transition when you own the setter and deferred value when you only receive the value.

    Authored expected output: A written comparison of control over the update versus deferring a received value.

    The distinction is where the state update happens. If you call the setter, use a transition. If the value arrives from outside, use a deferred value.

Common misconceptions

#
  • Fetching in an effect is always safe. Without cancellation, out-of-order responses cause stale data.
  • The use hook can be called in loops and conditions freely. It can be conditional, but the promise must be stable across renders.
  • useTransition makes code faster. It makes updates interruptible so the UI stays responsive; the work still happens.
  • useDeferredValue delays the value by a fixed time. It lags under load, not by a timer.

Follow-up practice

#
  • react-performance-and-identity
  • react-debugging-and-error-handling

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.