Skip to content

Commit f58c019

Browse files
committed
Add Reading a Promise from context section
1 parent 1e7b575 commit f58c019

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

  • src/content/reference/react

src/content/reference/react/use.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,33 @@ function Button({ show, children }) {
222222
223223
</Sandpack>
224224
225+
### Reading a Promise from context {/*reading-a-promise-from-context*/}
226+
227+
You can pass a Promise through context to share data without prop drilling. Pass the Promise as the context value, then call `use(context)` to read the Promise and `use(promise)` to read its resolved value:
228+
229+
```js
230+
import { use } from 'react';
231+
import { UserContext } from './UserContext';
232+
233+
function Profile() {
234+
const userPromise = use(UserContext);
235+
const user = use(userPromise);
236+
return <h1>{user.name}</h1>;
237+
}
238+
```
239+
240+
Wrap the components that read the Promise in [`<Suspense>`](/reference/react/Suspense) so only that subtree suspends while the Promise is pending. See [Usage (Promises)](#usage-promises) below for more on reading Promises with `use`.
241+
242+
<Pitfall>
243+
244+
Passing a Promise through context is convenient, but comes with trade-offs. Prefer passing the Promise as a [prop](#reading-a-promise-with-use) from a [Server Component](/reference/rsc/server-components) when possible.
245+
246+
* **Double unwrap.** Reading the value requires two calls: `use(context)` to get the Promise, then `use(promise)` to get its resolved value. The context value itself is not awaited.
247+
* **Revalidation scope.** Because the Promise is created in the component that provides it, revalidating the data requires re-rendering that component. Hoisting data into a component high in the tree means everything below it re-renders to update the data.
248+
* **One Promise per context.** Each piece of data needs its own context. Reaching for more contexts to share more data is usually a sign that the data should be fetched closer to where it's used.
249+
250+
</Pitfall>
251+
225252
---
226253
227254
## Usage (Promises) {/*usage-promises*/}

0 commit comments

Comments
 (0)