Sub topic 9
Choosing between use, useContext, and async/await
This chapter assumes you have read the earlier chapters in this tutorial. You should know how use reads a promise and a context, how Suspense and error boundaries react to a suspended or failed component, and why a promise must keep the same identity across renders. You should also know the difference between Server Components and Client Components. The chapter doesn't introduce new mechanics. It gives you a way to pick the right tool for a read and to spot the usual mistakes.
Three tools, two kinds of reads
React 19 gives you three ways to get a value into a component. Two of them read context and one reads asynchronous data. use can do both.
| Tool | Reads | Where it works | Can be conditional | Pauses rendering |
|---|---|---|---|---|
| `useContext` | Context | Client Components, any React version | No (Rules of Hooks) | No |
| `use(context)` | Context | Client Components, React 19 | Yes | No |
| `use(promise)` | A promise | Client Components, and Server Components | Yes | Yes, through Suspense |
| `await` | A promise | `async` Server Components and server functions | Yes (ordinary JavaScript) | Yes, in the server render |
The table gives the first rule of the chapter: the kind of component you are in removes some options before you compare anything else.
- A Client Component cannot be an
asyncfunction, so it cannot useawaitto read data while rendering. - A Server Component has no context to read, because it does not support
createContext. It can import values and call functions, but it has no Provider tree to read from.
That leaves a small set of real choices, which the rest of the chapter covers.
Choosing for context: useContext or use
For context, use(SomeContext) and useContext(SomeContext) return the same value. Both subscribe the component to the nearest matching Provider. Both re-render the component when the Provider's value changes. Neither is faster than the other.
The difference is where you may call them. useContext is a Hook, so it must run at the top level of a component, in the same order on every render. use is not bound by that rule. You can call it after an early return, inside an if, or inside a loop.
import { createContext, use, useContext } from 'react';
export const ThemeContext = createContext({ color: 'black' });
// Fine with useContext: the read is unconditional.
export function Title({ children }) {
const theme = useContext(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
// Needs use: the read only happens if there is something to render.
export function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}The decision rule for context:
- If the component always reads the context, either tool works. Keep
useContextwhen the surrounding code already uses it, since a mixed codebase gains nothing. - If the read sits behind a condition or an early return, use
use. A conditionaluseContextcall breaks the Rules of Hooks, and the linter will flag it. - If you must support a React version before 19, use
useContext.usedoes not exist there.
Moving a context read below an early return has one visible effect. When the early return fires, the component does not read the context at all. A change to the Provider value then does not re-render that component for that render path. This is usually what you want, and it is the reason to do it.
Context is not a data-loading channel
A common pattern is to put a promise in a Provider and call use on it in descendants. This works. Any component below the Provider can call use(PromiseContext) to get the promise and then call use on that promise. It is also easy to get wrong. The promise must be created once, outside the render of the component that owns the Provider, or it will be recreated and re-suspend. Reach for it only when many distant components need the same pending value. For one component, pass the promise as a prop.
Choosing for promises: use or await
The promise choice depends on where the code runs.
In a Server Component, prefer await
In a Server Component you can make the component async and write await. The code reads top to bottom, and try/catch works because await is ordinary language syntax.
async function getProduct(id) {
const response = await fetch(`https://api.example.com/products/${id}`);
if (!response.ok) {
throw new Error(`Product request failed with ${response.status}`);
}
return response.json();
}
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await getProduct(id);
return (
<article>
<h1>{product.name}</h1>
<p>{product.description}</p>
</article>
);
}React also lets a Server Component call use(promise). The docs recommend await there, with one practical difference in how rendering resumes. When a component hits await, rendering continues from that point once the promise resolves. When it hits use, React re-renders the component from the start once the promise resolves. For a component with expensive work before the read, await avoids repeating it. There is no benefit to use in a Server Component that you would not also get from await.
In a Client Component, use is your only render-time option
A Client Component cannot await during render. If it needs to read a promise as part of rendering, it calls use. Your own useEffect plus useState loading pattern still works for fetching on the client, but it is a different design. It renders first with empty state, runs the effect after paint, and then re-renders. use instead suspends and lets a Suspense boundary show the fallback. The effect pattern gives you more manual control and more code. use gives you less code, but the promise has to come from somewhere stable.
That requirement is the main gotcha.
The promise must come from somewhere stable
A Client Component must not create the promise it passes to use during its own render. Each render would produce a new promise. React would suspend on the new, pending promise, discard the work, and render again, which creates another new promise. React warns that a component was suspended by an uncached promise, and in the worst case the component never settles.
'use client';
import { use } from 'react';
// Wrong: fetchReviews runs on every render and returns a new promise each time.
export function Reviews({ productId }) {
const reviews = use(fetchReviews(productId));
return <ul>{reviews.map((r) => <li key={r.id}>{r.text}</li>)}</ul>;
}There are three sound sources for a promise in a Client Component.
- A parent Server Component. The server creates the promise and passes it as a prop. This is the preferred option when you have a server.
- A parent that creates it once. A parent can create the promise in an event handler or in lazily initialized state, then pass it down.
- A Suspense-compatible cache or data library. The library returns the same promise for the same key.
Here is the second option, with a promise held in state and replaced inside a transition when the user searches again.
'use client';
import { Suspense, startTransition, use, useState } from 'react';
async function fetchResults(query) {
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
if (!response.ok) {
throw new Error('Search failed');
}
return response.json();
}
function Results({ resultsPromise }) {
const results = use(resultsPromise);
return (
<ul>
{results.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}
export function Search() {
const [query, setQuery] = useState('react');
const [resultsPromise, setResultsPromise] = useState(() =>
fetchResults('react')
);
function handleSubmit(event) {
event.preventDefault();
startTransition(() => {
setResultsPromise(fetchResults(query));
});
}
return (
<form onSubmit={handleSubmit}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
<Suspense fallback={<p>Searching...</p>}>
<Results resultsPromise={resultsPromise} />
</Suspense>
</form>
);
}Two details matter here.
- The lazy initializer
() => fetchResults('react')runs once, on mount. WritinguseState(fetchResults('react'))would call the function on every render and throw away the extra promises. - The new promise is created in the event handler, not in render, so it has a stable identity for as long as the state holds it. The
startTransitionwrapper keeps the old results on screen while the new ones load. Without it, the Suspense boundary would swap in the fallback again.
Do not reach for useMemo to make the promise stable. React treats useMemo as a performance hint and may discard cached values, so it does not guarantee identity.
Streaming from server to client
The third promise pattern joins the first two. A Server Component starts a fetch and does not await it. It passes the pending promise to a Client Component, which reads it with use. React serializes the promise across the server and client boundary and streams the resolved value when it is ready. The rest of the page does not wait.
// app/page.jsx (Server Component)
import { Suspense } from 'react';
import { Reviews } from './Reviews';
async function fetchReviews(productId) {
const response = await fetch(
`https://api.example.com/products/${productId}/reviews`
);
if (!response.ok) {
throw new Error('Reviews request failed');
}
return response.json();
}
export default async function Page() {
const productId = 42;
const product = await fetch(
`https://api.example.com/products/${productId}`
).then((r) => r.json());
// Not awaited: the page can render before reviews arrive.
const reviewsPromise = fetchReviews(productId);
return (
<main>
<h1>{product.name}</h1>
<Suspense fallback={<p>Loading reviews...</p>}>
<Reviews reviewsPromise={reviewsPromise} />
</Suspense>
</main>
);
}// app/Reviews.jsx (Client Component)
'use client';
import { use } from 'react';
export function Reviews({ reviewsPromise }) {
const reviews = use(reviewsPromise);
return (
<ul>
{reviews.map((review) => (
<li key={review.id}>{review.text}</li>
))}
</ul>
);
}The page awaits the product because the heading needs it, and it streams the reviews because they can arrive later. Awaiting both would delay the whole response until the slower call finished. This is the main reason to prefer this pattern over a plain await: you choose, per piece of data, whether it blocks the shell.
Two limits apply. The promise must resolve to a value React can serialize, so plain objects, arrays, strings, numbers, and similar values are fine, while functions and class instances are not. The component that calls use must be a Client Component if it needs hooks or browser interactivity. If it only renders markup, it can be a Server Component that simply awaits.
Choosing by situation
The diagram collapses the rules above into one path.
Some common situations and their answers:
| Situation | Choice | Reason |
|---|---|---|
| Read a theme, always, in a Client Component | `useContext` or `use` | Same behavior, so follow the codebase |
| Read a theme only after a null check | `use(ThemeContext)` | `useContext` cannot follow a conditional return |
| Load the main content of a server-rendered page | `await` in an `async` Server Component | Simplest code, `try`/`catch` works |
| Load secondary content that may arrive late | Unawaited promise, `use` in a Client Component, inside Suspense | The shell is not blocked |
| Load data in a client-only app | A cache or library that returns stable promises, then `use` | Render-time promises are not stable |
| Fetch after a click | Create the promise in the handler, store it, `use` it | Identity is held in state |
| Need the error as a value | `.catch(() => fallbackValue)` on the promise, or `try`/`catch` around `await` | `use` cannot go in `try`/`catch` |
Error handling differs by tool
The error path is another reason to pick one tool over another.
- With
awaitin a Server Component, you can catch the error right there withtry/catchand render an alternative, or you can let it propagate to the nearest error boundary. - With
use, a rejected promise makesusethrow during render, and the nearest error boundary renders its fallback. You cannot wrapuseintry/catch. - To give a Client Component a fallback value instead of an error, attach
.catchto the promise before passing it down.
async function fetchReviews(productId) {
const response = await fetch(
`https://api.example.com/products/${productId}/reviews`
);
if (!response.ok) {
throw new Error('Reviews request failed');
}
return response.json();
}
// In the Server Component, before passing the promise to the Client Component:
const reviewsPromise = fetchReviews(42).catch(() => []);Choose the fallback value when an empty result is an acceptable page. Choose the error boundary when the user needs to see that something failed and perhaps retry.
Common mistakes
- Calling
usein an event handler, effect, ortryblock.useworks only while a component or a Hook is rendering, and it cannot sit intry/catch. Read the value during render and pass it to the handler through a closure. - Marking a Client Component
async. React does not support it. Move theawaitto a Server Component, or pass a promise down and useuse. - Creating the promise inside the component that calls
use. The result is a loop of suspensions. Create it in a parent, in an event handler, in state, or in a cache. - Awaiting everything on the server. Each
awaitthat the page does not need before sending the shell delays the first byte. Ask whether the content can stream. - Forgetting the Suspense boundary.
usesuspends, so without a boundary above it the suspension reaches the nearest one, possibly the root, and replaces more of the page than you intended. Place the boundary tightly around the component that suspends. - Expecting context in a Server Component. Pass the value as a prop instead.
Summary of the rules
- In a Server Component, use
await. Useuseonly if you have a specific reason. - In a Client Component, read promises with
use, and make sure the promise comes from a source that does not recreate it on every render. - To keep a slow request from blocking the page, start it in a Server Component, do not await it, and pass it to a Client Component wrapped in Suspense.
- For context,
useanduseContextare equivalent. Useusewhen the read is conditional. - Handle failures with an error boundary, a
.catchthat returns a fallback value, ortry/catcharoundawait. Nevertry/catcharounduse.
Exercise
A Client Component named Comments contains const comments = use(fetchComments(postId)); and the browser console warns that a component was suspended by an uncached promise. Name the cause and give two ways to fix it.
Show answer
fetchComments(postId) runs during render, so every render creates a new promise. React suspends on the new pending promise, discards the render, and tries again with another new promise. Fixes: (1) create the promise in a parent Server Component and pass it down as a prop; (2) create it once in a parent Client Component, for example in a lazy useState initializer or an event handler, and pass it as a prop. Using a Suspense-compatible cache that returns the same promise for the same key also works.
Exercise
A component returns null when items is empty and otherwise needs a LocaleContext value. Why can this not be written with useContext, and what do you write instead?
Show answer
A useContext call after an early return is conditional, which breaks the Rules of Hooks because Hooks must run in the same order on every render. Write const locale = use(LocaleContext); after the early return, since use may be called conditionally.
Exercise
A Server Component page shows a product title and a list of reviews. The reviews API is slow. Describe how to render the title immediately and still show the reviews when they arrive, and name the two components involved.
Show answer
In the Server Component, await the product data so the title renders, but call the reviews fetch without await to get a promise. Pass that promise as a prop to a Client Component such as Reviews, wrapped in <Suspense fallback={...}>. Reviews calls use(reviewsPromise). The page shell and title stream first, and the reviews stream in when the promise resolves. An error boundary can wrap the Suspense boundary to handle a rejection.
Exercise
You want a Client Component to show "No reviews available." when the reviews request fails, instead of showing an error boundary. Why does try { use(promise) } catch {} not work, and what does?
Show answer
use is not supported inside a try/catch block. Attach a .catch to the promise before it is passed to the component, for example fetchReviews(id).catch(() => []), so the promise resolves to a fallback value, and have the component render the message when the array is empty.