Sub topic 4
Where You Can Call use: Conditions, Loops, and Early Returns
What this chapter assumes
This chapter assumes you know the following:
- You can write function components and pass props.
- You have used
useStateanduseContext, and you know the Rules of Hooks (call Hooks at the top level, in the same order every render). - You know how promises and
asyncfunctions work in JavaScript. - You have a general idea of what a Suspense boundary does: it shows a fallback while something below it is not ready.
The previous chapters introduced use and Suspense. This chapter covers where a use call may appear. It also covers the places where it may not.
The rule you already know, and the exception
Every built-in Hook such as useState, useContext, and useEffect must be called at the top level of a component. You can't call it inside an if, a loop, or after an early return. React identifies each of these Hooks by its position in the call order, so the order has to be identical on every render.
use is the exception. React's documentation describes use as an API rather than a Hook. It has a Hook-like name, but it can be called inside conditions and loops, and after an early return.
It still has rules of its own:
- You must call it while a component or a custom Hook is rendering.
- You must not call it inside a
try/catchblock. - You must not call it in event handlers, effects, or other callbacks that run outside of rendering.
The rest of this chapter works through each rule and the reason behind it.
Why use can be conditional
Take useState first. It stores state, so React must connect each call to a saved slot. It does this by position: the first useState call gets the first slot, the second call gets the second slot. If a call is skipped on one render, every later call lands in the wrong slot.
use does not claim a slot in that sense. It is given a value to read, and what it does depends on that value:
- If you pass it a context, it returns the current value from the nearest provider. This is the same lookup
useContextperforms. There is no saved state to match up. - If you pass it a promise, React checks whether the promise has already resolved. If it has,
usereturns the result. If the promise is still pending, React suspends the component, which means it pauses rendering this component and shows the nearest Suspense fallback. When the promise settles, React tries to render the component again. If the promise rejected,usethrows the rejection reason, and the nearest error boundary handles it.
Because use does not depend on its position in the call order, skipping it on some renders is safe.
This also means use can be called after other code that might return early. The call still has to be reached during rendering.
Calling use after an early return
Consider a Heading component that renders nothing when it has no children. With useContext, you would have to read the theme before the early return, even though a null result never needs it:
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Heading({ children }) {
const theme = useContext(ThemeContext); // must come first
if (children == null) {
return null;
}
return <h1 style={{ color: theme.color }}>{children}</h1>;
}With use, you can put the early return first:
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>;
}The next chapter looks at context in more detail. For now, notice the placement: the use call comes after a return statement that might run.
Reading context is cheap, so this saves almost nothing at runtime in a simple case like this. The benefit is readability. Guard clauses (early returns for the "nothing to show" cases) can sit at the top of the function, and the real work follows them.
Calling use in a condition
You can read a promise or context inside an if. Here is a component that reads a promise only when a preview is switched on:
import { use } from 'react';
function Preview({ previewPromise, showPreview }) {
if (!showPreview) {
return <p>Preview is off.</p>;
}
const preview = use(previewPromise);
return <p>Preview: {preview}</p>;
}When showPreview is false, Preview never suspends, so no fallback appears. When it is true, the component suspends until the promise resolves.
Remember what the condition controls. It controls when this component waits on the promise. It does not control when the request starts. Whoever created previewPromise already started the work. If you want the request to begin only when the preview is shown, the code that creates the promise has to be conditional too. That depends on where the promise is created, which the "Keeping the promise stable across renders" chapter covers.
You can also place use inside a ternary or a logical expression:
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function Badge({ highlighted, label }) {
const color = highlighted ? use(ThemeContext).accent : 'gray';
return <span style={{ color }}>{label}</span>;
}This is valid. Even so, a plain if at the top of the function is usually easier to read than a use call buried in an expression. Prefer the form that makes the dependency obvious.
Calling use in a loop
You can also call use repeatedly in a loop. This is useful when a component receives several promises. The following example is complete and can run in a project that has React 19 and a bundler set up:
import { Suspense, use } from 'react';
import { createRoot } from 'react-dom/client';
function delay(value, ms) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
// Created once, outside any component, so the identities never change.
const commentPromises = [
delay('First!', 500),
delay('Nice post.', 1000),
delay('Thanks for sharing.', 1500),
];
function CommentList({ commentPromises }) {
const comments = [];
for (const promise of commentPromises) {
comments.push(use(promise));
}
return (
<ul>
{comments.map((comment, index) => (
<li key={index}>{comment}</li>
))}
</ul>
);
}
function App() {
return (
<Suspense fallback={<p>Loading comments...</p>}>
<CommentList commentPromises={commentPromises} />
</Suspense>
);
}
createRoot(document.getElementById('root')).render(<App />);Here is what happens when this code runs:
CommentListstarts rendering and callsuseon the first promise. It is pending, so the component suspends and the fallback appears.- After about 500 ms the first promise resolves. React renders
CommentListagain. The firstusecall returns right away. The secondusecall suspends, because that promise is still pending. - The same thing happens for the third promise.
- After about 1500 ms, all three promises are resolved and the full list appears.
All three timers started when the module loaded, so they ran in parallel. The total wait is about 1500 ms, not 3000 ms. The component only discovers each pending promise one at a time, but the work behind them was already running.
The loop would be slower if each promise were created inside the loop, because each request would start only after the previous one finished. That pattern is called a waterfall, and it is the main performance risk of using use in a loop.
A safer layout for lists
A loop over several promises gives you one all-or-nothing wait: no item shows until every item has resolved. If you want items to appear as they arrive, give each item its own component and its own Suspense boundary:
import { Suspense, use } from 'react';
function Comment({ commentPromise }) {
const comment = use(commentPromise);
return <li>{comment}</li>;
}
export function CommentList({ commentPromises }) {
return (
<ul>
{commentPromises.map((promise, index) => (
<Suspense key={index} fallback={<li>Loading...</li>}>
<Comment commentPromise={promise} />
</Suspense>
))}
</ul>
);
}Now each <li> appears when its own promise resolves. The loop is in the parent, which only passes props. The use call is in the child, where it is a plain call at the top level. Use this layout when partial results are useful. Use the single-component loop when you need all values before you can render anything.
One trap deserves a warning. You might want to combine the promises with Promise.all and call use once:
const all = use(Promise.all(commentPromises)); // Wrong: new promise on every renderPromise.all returns a new promise each time it runs. Created during render, it has a new identity on every render, and React treats it as a different promise each time. The "Keeping the promise stable across renders" chapter explains this problem in detail. If you need the combined result, create the Promise.all once, outside the component or in a parent that holds it stable, and pass it down.
Where use is not allowed
The relaxed rules cover conditions, loops, and early returns. They do not cover everything. This table lists the places where use is still not supported:
| Location | Allowed? | What to do instead |
|---|---|---|
| Top level of a component | Yes | Nothing special needed. |
| Inside `if`, ternary, or loop in a component | Yes | Nothing special needed. |
| After an early `return` in a component | Yes | Nothing special needed. |
| Inside a custom Hook | Yes | The Hook must itself be called during render. |
| Inside a `try`/`catch` block | No | Use an error boundary, or attach `.catch` to the promise. |
| Inside an event handler | No | Call `use` during render and use the value in the handler. |
| Inside `useEffect` or other effect callbacks | No | Read the value during render and list it as a dependency. |
| Inside an `async` Server Component | No | Use `await` instead. |
| Outside any component or Hook | No | Move the call into a component or Hook. |
No try/catch
This code is not supported:
import { use } from 'react';
function Message({ messagePromise }) {
try {
const message = use(messagePromise); // not supported inside try/catch
return <p>Here is the message: {message}</p>;
} catch (error) {
return <p>Could not load the message.</p>;
}
}Suspending works by interrupting the render. A catch block could intercept that interruption and break it. So React does not support use inside try/catch, even though it looks like the natural way to handle a failed promise.
There are two supported options:
- Put an error boundary above the component. If the promise rejects,
usethrows the rejection reason and the boundary renders its fallback. - Attach
.catchto the promise before it is passed touse, so the promise resolves to a fallback value instead of rejecting.
const messagePromise = new Promise((resolve, reject) => {
// ...
}).catch(() => 'No message found.');The "Handling rejected promises" chapter works through both options with full examples.
No event handlers or effects
use reads a value for the render that is happening now. An event handler runs later, in response to a click, and an effect runs after the render has been committed. Neither is a place where React can suspend the component.
The fix is to read the value during render, then use the result inside the handler:
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function SaveButton({ onSave }) {
const theme = use(ThemeContext); // read during render
function handleClick() {
onSave({ theme: theme.name }); // use the value later
}
return (
<button style={{ color: theme.color }} onClick={handleClick}>
Save
</button>
);
}For context, useContext works in the same place and is equally valid here.
No use inside async components
An async Server Component can use await directly, and await is the better tool there. React documentation recommends async/await in Server Components. Rendering continues from the point where the await happened, whereas use re-renders the component once the data has resolved. Client Components cannot be async functions at all, which is why use exists for them.
The linter helps
The react-hooks ESLint rules know about use. They accept it inside conditions and loops, and they warn when use appears outside a component or a Hook. A helper function that you call from a component but name in lowercase, like readSomething, can trigger this warning. If you see it, rename the function to a Hook name that starts with use, or move the use call into the component body.
A quick way to decide
Common errors
- A new promise on every render. The component suspends, the promise settles, React renders again, and the component creates another new promise and suspends again. The result is an endless loop of fallbacks. Pass promises in as props from a stable source, or create them outside the component.
- A
usecall insidetry/catch. React does not support this. Move error handling to an error boundary or to the promise. - Reading a promise in an event handler. The handler runs outside rendering. Read the value during render and use the result in the handler.
- Believing the condition delays the request. Putting
usebehind anifdelays suspension, not the network call. The promise exists before theifis checked. - Looping with
usewhen one slow item blocks the rest. A single loop shows nothing until every promise has resolved. Use one component with one Suspense boundary per item when partial results are better.
Exercise
A component receives a prop userPromise and a boolean prop enabled. Write the body of the component so that it renders <p>Disabled</p> without reading the promise when enabled is false, and otherwise renders the user's name from use(userPromise).name. Does the enabled check stop the request from starting?
Show answer
function UserName({ userPromise, enabled }) { if (!enabled) { return <p>Disabled</p>; } const user = use(userPromise); return <p>{user.name}</p>; } The check does not stop the request. The promise was created by the parent before this component ran, so the request is already in progress. The check only means this component does not suspend while enabled is false.
Exercise
This component is meant to show a fallback text when the promise rejects. Explain why it is not supported and give two ways to fix it. function Price({ pricePromise }) { try { const price = use(pricePromise); return <p>{price}</p>; } catch { return <p>Price unavailable</p>; } }
Show answer
React does not support use inside a try/catch block, because suspending works by interrupting the render and a catch block could swallow that interruption. Fix 1: remove the try/catch and wrap the component in an error boundary, so a rejected promise makes the boundary show its fallback. Fix 2: attach a catch to the promise before passing it in, for example pricePromise.catch(() => 'Price unavailable'), so the promise resolves to a fallback value and use returns it.
Exercise
A component calls use(Promise.all(promises)) directly in its body. Why does this cause trouble, and what is the correct way to get the combined result?
Show answer
Promise.all returns a new promise every time it runs. Created during render in a Client Component, it has a new identity on every render, so React treats it as a different promise each time. The component suspends, re-renders, creates yet another promise, and suspends again. To fix it, create the Promise.all once outside the component or in a parent that keeps it stable, then pass it down as a prop and call use on that stable promise.