Sub topic 9
Choosing between use, useContext, and async/await
This chapter assumes you know function components and props, useState and useContext, JavaScript promises and async functions, and what a Suspense boundary does. By now you have seen use read promises and context. The remaining question is which tool to pick in a given situation.
The three tools at a glance
Each tool reads a value, but they work in different places and wait in different ways.
| Tool | Reads | Where it works | How it waits |
|---|---|---|---|
| `use` | A promise or a context | Client Components and Server Components, in conditions, loops, and after early returns | Suspends the component and shows the nearest Suspense fallback |
| `useContext` | A context only | Client Components, at the top level of the component | Does not wait. The value is available immediately |
| `async`/`await` | A promise | Server Components only | Pauses the component function on the server until the promise resolves |
The main difference is that useContext and use for context never wait. Reading a promise is the only case that involves waiting, and there you choose between use and await.
Choosing for context
For context, use(Context) and useContext(Context) return the same value. The difference is where you may call them. useContext follows the rules of Hooks, so it must run at the top level, before any early return. use has no such limit.
Prefer use when the context is needed only on some code paths:
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}With useContext, you would have to read the context before the early return, even when the component renders nothing. Either tool is correct when the read is unconditional. In new code, use is the more flexible choice, and existing useContext calls need no migration.
Choosing for promises
The choice depends on where the component runs.
In a Server Component
A Server Component can be an async function, so you can await the data directly:
async function Message() {
const response = await fetch('https://example.com/api/message');
const text = await response.text();
return <p>Here is the message: {text}</p>;
}Use await when this component cannot render without the data, and blocking on it is acceptable. React will not send this component's output until the promise resolves. A Suspense boundary above it can still stream the rest of the page.
In a Client Component
Client Components cannot be async functions, so await is not available. Use use instead. The promise must keep a stable identity across renders. Do not create it during render in the Client Component, because each render makes a new promise and the component suspends again.
Receive the promise as a prop, or take it from a cache or a library that returns stable promises:
import { Suspense, use } from 'react';
function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>Here is the message: {message}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}Across the server and client boundary
When a Server Component starts a fetch but does not await it, it can pass the promise to a Client Component. The Client Component reads it with use. The server renders the rest of the page without waiting, and the data streams in later.
import { Suspense } from 'react';
import { Message } from './Message';
async function fetchMessage() {
const response = await fetch('/api/message');
if (!response.ok) {
throw new Error('Request failed');
}
return response.text();
}
export default function App() {
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}This is a sketch. Message must be a Client Component, and the fetch URL must resolve on the server.
Prefer this pattern when the data is not needed for the first paint, or when the Client Component needs the data for interactivity. If a Server Component can render the data without client code, await is simpler.
A decision flow
Common mistakes
- Marking a Client Component
asyncto useawait. React does not support this. Useusewith a promise passed down or cached. - Calling
useon a promise created inside the same Client Component's render. The promise changes on every render, so the component never settles. - Wrapping
useintry/catch. This is not supported. Handle failures with an error boundary, or attach.catchto the promise before passing it in. - Forgetting the Suspense boundary. Without one above the component, there is no fallback to show while the promise is pending.
Exercises
Exercise
A Client Component needs to read a theme context, but only after it has checked that its user prop is not null and returned early otherwise. Which API should you use, and why?
Show answer
Use use(ThemeContext). useContext must be called at the top level before any early return, while use can be called after the early return, so the context is read only when the component renders its content.
Exercise
A Server Component fetches a list of products and renders them as plain HTML. No client code is involved. Which tool reads the data: use or await? Which one fits if the same data must instead be passed to an interactive Client Component without blocking the page?
Show answer
Use await in the async Server Component for the plain HTML case. For the Client Component case, start the fetch in the Server Component without awaiting it, pass the promise as a prop, and read it with use inside a Suspense boundary.