Sub topic 4
Where you can call use: conditions, loops, and early returns
This chapter assumes you can write function components, you have used useState and useContext, and you know how promises and Suspense work at a basic level. It covers the rules for where use may appear in a component and why those rules differ from the rules for other Hooks.
The rule you already know
Hooks such as useState and useContext must run in the same order on every render. React matches each call to stored state by its position in that order. For this reason you can't call them inside an if, a loop, or after an early return.
use is not bound by that restriction. It is still called from a component or a custom Hook, and it is still named like a Hook. But React does not track it by call position, so you can call it conditionally.
Why use can be conditional
useState needs a slot of stored state, and that slot is found by call order. use has no slot. When you pass it a promise, React either returns the resolved value or suspends the component. When you pass it a context, React reads the current value directly. No per-call bookkeeping depends on order.
Calling use after a condition
This component renders nothing unless show is true. It reads the promise only when it needs the data.
import { use } from 'react';
function Comments({ commentsPromise, show }) {
if (!show) {
return null;
}
const comments = use(commentsPromise);
return (
<ul>
{comments.map((comment) => (
<li key={comment.id}>{comment.text}</li>
))}
</ul>
);
}The same pattern works for context, which the next chapter covers in detail. A Heading component can return null when it has no children and only then call use(ThemeContext). With useContext, the early return would have to come after the call, so the context would be read every time.
Calling use in a loop
You can call use once per item in a list. Here each element of pricePromises is a promise for a number.
import { use } from 'react';
function Total({ pricePromises }) {
let total = 0;
for (const pricePromise of pricePromises) {
total += use(pricePromise);
}
return <p>Total: {total}</p>;
}Wrap Total in a Suspense boundary. If the first promise is still pending, the component suspends. When it resolves, React renders Total again from the top, and the loop continues to the next promise.
import { Suspense } from 'react';
export function Cart({ pricePromises }) {
return (
<Suspense fallback={<p>Calculating...</p>}>
<Total pricePromises={pricePromises} />
</Suspense>
);
}The promises in the array must already exist when Total renders, which means something outside it started the requests. If you created each promise inside the loop, the requests would start one after another and the code would also break the identity rule covered in a later chapter.
What use cannot do
Flexible does not mean unrestricted. These limits apply:
| Where | Allowed? | Reason |
|---|---|---|
| Top level of a component | Yes | Normal use |
| Inside `if`, `switch`, or ternary | Yes | No call-order tracking |
| Inside `for` or `while` loops | Yes | No call-order tracking |
| After an early `return` | Yes | Only reached when needed |
| Inside a custom Hook | Yes | Hooks run during render |
| Inside `try`/`catch` | No | Suspending works by throwing |
| Inside an event handler | No | Not running during render |
| Inside `useEffect` or `useMemo` callbacks | No | Not running during render |
| In a component that is an `async` function (Client Component) | No | Client Components cannot be async |
The try/catch restriction
When use suspends, React interrupts rendering in a way that a catch block would swallow. React therefore does not support use inside try/catch. This code is wrong:
function Message({ messagePromise }) {
try {
const message = use(messagePromise); // Not supported
return <p>{message}</p>;
} catch (error) {
return <p>Failed</p>;
}
}To handle a rejected promise, use an error boundary or attach .catch to the promise before passing it in. A later chapter covers both.
Event handlers and effects
use only works while React is rendering. If a click handler needs a value, read it with use during render and let the handler close over the result:
function SaveButton({ settingsPromise }) {
const settings = use(settingsPromise);
function handleClick() {
console.log('Saving with', settings.mode);
}
return <button onClick={handleClick}>Save</button>;
}Where the call is allowed
The diagram summarizes the decision.
A common mistake: conditional use is not conditional Suspense
Calling use after a condition does not skip the Suspense boundary. If the branch with use runs and the promise is pending, the component suspends exactly as before. The condition only decides whether the read happens at all.
Also remember that a suspended component does not keep its local variables. When the promise resolves, React runs the whole function again. Code before the use call runs once for each attempt, so keep it free of side effects.
Linting
The react-hooks ESLint rules know that use is allowed in conditions and loops. They still report use inside try/catch, in event handlers, and in non-component functions. Treat those warnings as real errors.
Exercise
A component receives a userPromise prop and a boolean isVisible. You want it to read the promise only when isVisible is true. Write the component body, and name one place where you could not call use even though the code is otherwise the same.
Show answer
Return early, then call use:
function Profile({ userPromise, isVisible }) {
if (!isVisible) {
return null;
}
const user = use(userPromise);
return <p>{user.name}</p>;
}
This is valid because use does not depend on call order. You could not call use inside a try/catch block in this component, inside an onClick handler, or inside a useEffect callback. use must run during render and outside try/catch.