React / 91
use(): read a promise or context
React 19's use() reads a promise, suspending until it resolves, or reads context, even inside an if. The one rule is that the promise must outlive the render.
Reading a promise
import { use } from "react";
export default function Recipe({ recipePromise }) {
const recipe = use(recipePromise); // waits here until it resolves
return <h2>{recipe.name}</h2>;
}While the promise is pending, the component suspends: React stops rendering it and shows the nearest <Suspense> fallback instead. When the promise resolves, React renders Recipe again, and this time use returns the value.
pending
Suspense
fulfilled
use() returns the value
rejected
Error boundary
<ErrorBoundary message="Couldn't load the recipe.">
<Suspense fallback={<p>Loading recipe…</p>}>
<Recipe recipePromise={recipePromise} />
</Suspense>
</ErrorBoundary>ErrorBoundary is the class from Error boundaries. You can't use try/catch around use, so the boundary is how you catch a rejected promise.
The one rule: the promise must outlive the render
created during render ✗
use(fetchReviews())A brand-new promise again
created once, outside render ✓
const p = fetchReviews() // in a click, loader or cacheuse(p)The same promise, now resolved
So where can a stable promise come from?
- An event handler, stored in state:
onClick={() => setPromise(fetchRecipe(id))}. That's what the demo below does. - A cache that hands back the same promise for the same input.
- A framework or library: a router loader, a Server Component passing a promise down, or a Suspense-ready data library such as TanStack Query.
const cache = new Map();
export function fetchRecipe(id) {
if (!cache.has(id)) {
const promise = fetch(`https://dummyjson.com/recipes/${id}`).then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
});
cache.set(id, promise);
}
return cache.get(id);
}Now use(fetchRecipe(id)) is safe to write in render, because the second call returns the first promise. A real app also needs to expire old entries and retry failures, which is why libraries and frameworks usually own this cache.
use(promise) with Suspense
Try itNo promise yet. Nothing has been requested.
Reading context, even inside an if
use(SomeContext) reads context just like useContext. Unlike a Hook, it can sit inside a condition or loop:
import { use } from "react";
import { CurrencyContext } from "./CurrencyContext.js";
export default function Price({ amount, showCurrency }) {
if (!showCurrency) return <span>{amount}</span>;
const currency = use(CurrencyContext); // fine after an early return
return <span>{currency} {amount}</span>;
}With useContext, that early return before the Hook call would break the rules of Hooks. With use, it's allowed.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
