You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/reference/react/use.md
+27Lines changed: 27 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -222,6 +222,33 @@ function Button({ show, children }) {
222
222
223
223
</Sandpack>
224
224
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
+
functionProfile() {
234
+
constuserPromise=use(UserContext);
235
+
constuser=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.
0 commit comments