Merge pull request #3338 from Vages/patch-1

Explain difference between contexts and stores
pull/3346/head
Rich Harris 5 years ago committed by GitHub
commit e9b59f72dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -35,7 +35,6 @@ The markers can now add themselves to the map.
> A more finished version of `<MapMarker>` would also handle removal and prop changes, but we're only demonstrating context here. > A more finished version of `<MapMarker>` would also handle removal and prop changes, but we're only demonstrating context here.
## Context keys ## Context keys
In `mapbox.js` you'll see this line: In `mapbox.js` you'll see this line:
@ -46,4 +45,12 @@ const key = {};
We can use anything as a key — we could do `setContext('mapbox', ...)` for example. The downside of using a string is that different component libraries might accidentally use the same one; using an object literal means the keys are guaranteed not to conflict in any circumstance (since an object only has referential equality to itself, i.e. `{} !== {}` whereas `"x" === "x"`), even when you have multiple different contexts operating across many component layers. We can use anything as a key — we could do `setContext('mapbox', ...)` for example. The downside of using a string is that different component libraries might accidentally use the same one; using an object literal means the keys are guaranteed not to conflict in any circumstance (since an object only has referential equality to itself, i.e. `{} !== {}` whereas `"x" === "x"`), even when you have multiple different contexts operating across many component layers.
> Remember that context is not inherently reactive. If you need context values to be reactive then you can pass a store into context, which *will* be reactive. ## Contexts vs. stores
Contexts and stores seem similar. They differ in that stores are available to *any* part of an app, while a context is only available to *a component and its descendants*. This can be helpful if you want to use several instances of a component without the state of one interfering with the state of the others.
In fact, you might use the two together. Since context is not reactive, values that change over time should be represented as stores:
```js
const { these, are, stores } = getContext(...);
```

Loading…
Cancel
Save