React Foundations · Async Data

Reading a promise with use

use() with a promise

Reading a promise with use

Fetching data in React used to be a pile of bookkeeping. You needed an Effect to start the request, a flag for loading, another for the error, and a cleanup check to ignore late responses. Three pieces of state, all kept in step by hand.

The use hook reads a promise straight through, without any of that:

import { use } from 'react';

function Message() {
  const value = use(messagePromise);
  return <p>{value}</p>;
}

While the promise is still pending, React suspends the component. It does not render a half-finished Message; it renders the nearest <Suspense> fallback instead:

<Suspense fallback={<p>Loading…</p>}>
  <Message />
</Suspense>

When the promise settles, React re-renders Message and use returns the resolved value. No loading flag, no useEffect. use can also be called conditionally and after an early return, which sets it apart from every hook.

One rule keeps this working: the promise must be stable. Create it outside the component, or cache it, so a re-render does not hand use a brand-new promise and suspend again forever.

Your job is to read a promise with use behind a Suspense boundary.

Challenge

A message is stuck on its loading fallback and never shows the value the promise resolves to. Export an App component from App.jsx that wraps a Message child in a <Suspense> whose fallback is <p>Loading…</p>. Message reads the module's message promise with use and renders the value in a paragraph.

The Test resolves the promise and looks for the paragraph to read Hello from data. The starter only ever renders the fallback, so the Test fails. Make the promise reach Message through use.

App.jsx
export function App() {
  return <p>Loading…</p>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.