The React use() Hook: Reading Promises and Context
use is a React API that reads the value of a resource: a promise or a context. It's unusual because you can call it inside conditions and loops.
Reading a promise
When the promise is pending, the component suspends and the nearest <Suspense> boundary shows its fallback. When it resolves, the component renders with the value.
import { use, Suspense } from 'react';
function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return comments.map((c) => <p key={c.id}>{c.text}</p>);
}
export default function Post({ post, commentsPromise }) {
return (
<article>
<h1>{post.title}</h1>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
</article>
);
}
Where should the promise come from?
Don't create the promise inside the component that calls use: a new promise on every render means it will suspend forever. Create it in a parent, a Server Component, a router loader or a cached data layer, and pass it down.
// Server Component (e.g. Next.js App Router): start the fetch, don't await it
export default async function Page({ params }) {
const { id } = await params;
const post = await getPost(id);
const commentsPromise = getComments(id); // streams in later
return <Post post={post} commentsPromise={commentsPromise} />;
}
Errors
If the promise rejects, the nearest Error Boundary renders. Wrap Suspense boundaries in an error boundary for a friendly message.
Reading context conditionally
function Price({ amount, showCurrency }) {
if (!showCurrency) return amount;
const { currency } = use(SettingsContext); // allowed after an early return
return `${currency} ${amount}`;
}
use can't be called in try/catch blocks; use an error boundary instead.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.