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
When passing multiple values (as an `array` or `object`), it is recommended to use a [store](/reference/component-apis/create-context#usage).
65
+
</Callout>
79
66
80
67
## Consuming context
81
68
82
69
Once the values are available to all the components in the context's component tree, they can be accessed using the [`useContext`](/reference/component-apis/use-context) utility.
83
70
This utility takes in the context object and returns the value(s) passed to the `Provider`:
@@ -211,7 +158,7 @@ export function CounterProvider(props) {
211
158
}
212
159
```
213
160
214
-
## Updating context values
161
+
## Updating Context Values
215
162
216
163
[Signals](/concepts/signals) offer a way to synchronize and manage data shared across your components using context.
217
164
You can pass a signal directly to the `value` prop of the `Provider` component, and any changes to the signal will be reflected in all components that consume the context.
@@ -290,21 +235,50 @@ When working with TypeScript, this can introduce type issues that make it diffic
290
235
291
236
To solve this issue, a default value can be specified when creating a context object, or errors can be handled manually through the use of a custom `useMyContext` utility:
thrownewError("useMyContext must be used within a MyContext.Provider");
243
+
244
+
if (!value) {
245
+
thrownewError("Missing context Provider");
302
246
}
247
+
303
248
returnvalue;
304
249
}
305
250
306
251
function Child() {
307
252
const value =useMyContext();
253
+
308
254
return <div>{value}</div>;
309
255
}
310
256
```
257
+
258
+
## Common issues with `createContext` and `useContext`
259
+
260
+
If no default value is passed to `createContext`, it is possible for `useContext` to return `undefined`.
261
+
262
+
<Callouttype="info"title="More on default values">
263
+
Read more about default values in the [`createContext`](/reference/component-apis/create-context) entry.
264
+
</Callout>
265
+
266
+
Because of this, if an initial value was not passed to `createContext`, the TS type signature of `useContext` will indicate that
267
+
the value returned might be `undefined` (as mentioned above).
268
+
This can be quite annoying when you want to use the context inside a component, and particularly when immediately destructuring the context.
269
+
Additionally, if you use `useContext` and it returns `undefined` (which is often, but not always, the result of a bug), the error message thrown at runtime can be confusing.
270
+
271
+
The most common solution for it is to wrap all uses of `useContext` in a function that will explicitly throw a helpful error if the context is `undefined`.
272
+
This also serves to narrow the type returned, so TS doesn't complain.
0 commit comments