|
2 | 2 | title: Context
|
3 | 3 | ---
|
4 | 4 |
|
5 |
| -<!-- - get/set/hasContext |
6 |
| -- how to use, best practises (like encapsulating them) --> |
| 5 | +Context allows components to access values owned by parent components without passing them down as props (potentially through many layers of intermediate components, known as 'prop-drilling'). The parent component sets context with `setContext(key, value)`... |
7 | 6 |
|
8 |
| -Most state is component-level state that lives as long as its component lives. There's also section-wide or app-wide state however, which also needs to be handled somehow. |
9 |
| - |
10 |
| -The easiest way to do that is to create global state and just import that. |
| 7 | +```svelte |
| 8 | +<!--- file: Parent.svelte ---> |
| 9 | +<script> |
| 10 | + import { setContext } from 'svelte'; |
11 | 11 |
|
12 |
| -```ts |
13 |
| -/// file: state.svelte.js |
14 |
| -export const myGlobalState = $state({ |
15 |
| - user: { |
16 |
| - /* ... */ |
17 |
| - } |
18 |
| - /* ... */ |
19 |
| -}); |
| 12 | + setContext('my-context', 'hello from Parent.svelte'); |
| 13 | +</script> |
20 | 14 | ```
|
21 | 15 |
|
| 16 | +...and the child retrieves it with `getContext`: |
| 17 | + |
22 | 18 | ```svelte
|
23 |
| -<!--- file: App.svelte ---> |
| 19 | +<!--- file: Child.svelte ---> |
24 | 20 | <script>
|
25 |
| - import { myGlobalState } from './state.svelte.js'; |
26 |
| - // ... |
| 21 | + import { getContext } from 'svelte'; |
| 22 | +
|
| 23 | + const message = getContext('my-context'); |
27 | 24 | </script>
|
| 25 | +
|
| 26 | +<h1>{message}, inside Child.svelte</h1> |
28 | 27 | ```
|
29 | 28 |
|
30 |
| -This has a few drawbacks though: |
| 29 | +This is particularly useful when `Parent.svelte` is not directly aware of `Child.svelte`, but instead renders it as part of a `children` [snippet](snippet) ([demo](/playground/untitled#H4sIAAAAAAAAE42Q3W6DMAyFX8WyJgESK-oto6hTX2D3YxcM3IIUQpR40yqUd58CrCXsp7tL7HNsf2dAWXaEKR56yfTBGOOxFWQwfR6Qz8q1XAHjL-GjUhvzToJd7bU09FO9ctMkG0wxM5VuFeeFLLjtVK8ZnkpNkuGo-w6CTTJ9Z3PwsBAemlbUF934W8iy5DpaZtOUcU02-ZLcaS51jHEkTFm_kY1_wfOO8QnXrb8hBzDEc6pgZ4gFoyz4KgiD7nxfTe8ghqAhIfrJ46cTzVZBbkPlODVJsLCDO6V7ZcJoncyw1yRr0hd1GNn_ZbEM3I9i1bmVxOlWElUvDUNHxpQngt3C4CXzjS1rtvkw22wMrTRtTbC8Lkuabe7jvthPPe3DofYCAAA=)): |
| 30 | + |
| 31 | +```svelte |
| 32 | +<Parent> |
| 33 | + <Child /> |
| 34 | +</Parent> |
| 35 | +``` |
31 | 36 |
|
32 |
| -- it only safely works when your global state is only used client-side - for example, when you're building a single page application that does not render any of your components on the server. If your state ends up being managed and updated on the server, it could end up being shared between sessions and/or users, causing bugs |
33 |
| -- it may give the false impression that certain state is global when in reality it should only be used in a certain part of your app |
| 37 | +The key (`'my-context'`, in the example above) and the context itself can be any JavaScript value. |
34 | 38 |
|
35 |
| -To solve these drawbacks, Svelte provides a few `context` primitives which alleviate these problems. |
| 39 | +In addition to [`setContext`](svelte#setContext) and [`getContext`](svelte#getContext), Svelte exposes [`hasContext`](svelte#hasContext) and [`getAllContexts`](svelte#getAllContexts) functions. |
36 | 40 |
|
37 |
| -## Setting and getting context |
| 41 | +## Using context with state |
38 | 42 |
|
39 |
| -To associate an arbitrary object with the current component, use `setContext`. |
| 43 | +You can store reactive state in context ([demo](/playground/untitled#H4sIAAAAAAAAE41R0W6DMAz8FSuaBNUQdK8MkKZ-wh7HHihzu6hgosRMm1D-fUpSVNq12x4iEvvOx_kmQU2PIhfP3DCCJGgHYvxkkYid7NCI_GUS_KUcxhVEMjOelErNB3bsatvG4LW6n0ZsRC4K02qpuKqpZtmrQTNMYJA3QRAs7PTQQxS40eMCt3mX3duxnWb-lS5h7nTI0A4jMWoo4c44P_Hku-zrOazdy64chWo-ScfRkRgl8wgHKrLTH1OxHZkHgoHaTraHcopXUFYzPPVfuC_hwQaD1GrskdiNCdQwJljJqlvXfyqVsA5CGg0uRUQifHw56xFtciO75QrP07vo_JXf_tf8yK2ezDKY_ZWt_1y2qqYzv7bI1IW1V_sN19m-07wCAAA=))... |
40 | 44 |
|
41 | 45 | ```svelte
|
42 | 46 | <script>
|
43 | 47 | import { setContext } from 'svelte';
|
| 48 | + import Child from './Child.svelte'; |
44 | 49 |
|
45 |
| - setContext('key', value); |
| 50 | + let counter = $state({ |
| 51 | + count: 0 |
| 52 | + }); |
| 53 | +
|
| 54 | + setContext('counter', counter); |
46 | 55 | </script>
|
| 56 | +
|
| 57 | +<button onclick={() => counter.count += 1}> |
| 58 | + increment |
| 59 | +</button> |
| 60 | +
|
| 61 | +<Child /> |
| 62 | +<Child /> |
| 63 | +<Child /> |
47 | 64 | ```
|
48 | 65 |
|
49 |
| -The context is then available to children of the component (including slotted content) with `getContext`. |
| 66 | +...though note that if you _reassign_ `counter` instead of updating it, you will 'break the link' — in other words instead of this... |
50 | 67 |
|
51 | 68 | ```svelte
|
52 |
| -<script> |
53 |
| - import { getContext } from 'svelte'; |
54 |
| -
|
55 |
| - const value = getContext('key'); |
56 |
| -</script> |
| 69 | +<button onclick={() => counter = { count: 0 }}> |
| 70 | + reset |
| 71 | +</button> |
57 | 72 | ```
|
58 | 73 |
|
59 |
| -`setContext` and `getContext` solve the above problems: |
| 74 | +...you must do this: |
60 | 75 |
|
61 |
| -- the state is not global, it's scoped to the component. That way it's safe to render your components on the server and not leak state |
62 |
| -- it's clear that the state is not global but rather scoped to a specific component tree and therefore can't be used in other parts of your app |
| 76 | +```svelte |
| 77 | +<button onclick={() => +++counter.count = 0+++}> |
| 78 | + reset |
| 79 | +</button> |
| 80 | +``` |
63 | 81 |
|
64 |
| -> [!NOTE] `setContext`/`getContext` must be called during component initialisation. |
| 82 | +Svelte will warn you if you get it wrong. |
65 | 83 |
|
66 |
| -Context is not inherently reactive. If you need reactive values in context then you can pass a `$state` object into context, whose properties _will_ be reactive. |
| 84 | +## Type-safe context |
67 | 85 |
|
68 |
| -```svelte |
69 |
| -<!--- file: Parent.svelte ---> |
70 |
| -<script> |
71 |
| - import { setContext } from 'svelte'; |
| 86 | +A useful pattern is to wrap the calls to `setContext` and `getContext` inside helper functions that let you preserve type safety: |
72 | 87 |
|
73 |
| - let value = $state({ count: 0 }); |
74 |
| - setContext('counter', value); |
75 |
| -</script> |
| 88 | +```js |
| 89 | +/// file: context.js |
| 90 | +// @filename: ambient.d.ts |
| 91 | +interface User {} |
76 | 92 |
|
77 |
| -<button onclick={() => value.count++}>increment</button> |
78 |
| -``` |
| 93 | +// @filename: index.js |
| 94 | +// ---cut--- |
| 95 | +import { getContext, setContext } from 'svelte'; |
79 | 96 |
|
80 |
| -```svelte |
81 |
| -<!--- file: Child.svelte ---> |
82 |
| -<script> |
83 |
| - import { getContext } from 'svelte'; |
| 97 | +let key = {}; |
84 | 98 |
|
85 |
| - const value = getContext('counter'); |
86 |
| -</script> |
| 99 | +/** @param {User} user */ |
| 100 | +export function setUserContext(user) { |
| 101 | + setContext(key, user); |
| 102 | +} |
87 | 103 |
|
88 |
| -<p>Count is {value.count}</p> |
| 104 | +export function getUserContext() { |
| 105 | + return /** @type {User} */ (getContext(key)); |
| 106 | +} |
89 | 107 | ```
|
90 | 108 |
|
91 |
| -To check whether a given `key` has been set in the context of a parent component, use `hasContext`. |
| 109 | +## Replacing global state |
92 | 110 |
|
93 |
| -```svelte |
94 |
| -<script> |
95 |
| - import { hasContext } from 'svelte'; |
| 111 | +When you have state shared by many different components, you might be tempted to put it in its own module and just import it wherever it's needed: |
96 | 112 |
|
97 |
| - if (hasContext('key')) { |
98 |
| - // do something |
| 113 | +```js |
| 114 | +/// file: state.svelte.js |
| 115 | +export const myGlobalState = $state({ |
| 116 | + user: { |
| 117 | + // ... |
99 | 118 | }
|
100 |
| -</script> |
| 119 | + // ... |
| 120 | +}); |
101 | 121 | ```
|
102 | 122 |
|
103 |
| -You can also retrieve the whole context map that belongs to the closest parent component using `getAllContexts`. This is useful, for example, if you programmatically create a component and want to pass the existing context to it. |
| 123 | +In many cases this is perfectly fine, but there is a risk: if you mutate the state during server-side rendering (which is discouraged, but entirely possible!)... |
104 | 124 |
|
105 | 125 | ```svelte
|
| 126 | +<!--- file: App.svelte ----> |
106 | 127 | <script>
|
107 |
| - import { getAllContexts } from 'svelte'; |
| 128 | + import { myGlobalState } from 'svelte'; |
108 | 129 |
|
109 |
| - const contexts = getAllContexts(); |
| 130 | + let { data } = $props(); |
| 131 | +
|
| 132 | + if (data.user) { |
| 133 | + myGlobalState.user = data.user; |
| 134 | + } |
110 | 135 | </script>
|
111 | 136 | ```
|
112 | 137 |
|
113 |
| -## Encapsulating context interactions |
114 |
| - |
115 |
| -The above methods are very unopinionated about how to use them. When your app grows in scale, it's worthwhile to encapsulate setting and getting the context into functions and properly type them. |
116 |
| - |
117 |
| -```ts |
118 |
| -// @errors: 2304 |
119 |
| -import { getContext, setContext } from 'svelte'; |
120 |
| - |
121 |
| -let userKey = Symbol('user'); |
122 |
| - |
123 |
| -export function setUserContext(user: User) { |
124 |
| - setContext(userKey, user); |
125 |
| -} |
126 |
| - |
127 |
| -export function getUserContext(): User { |
128 |
| - return getContext(userKey) as User; |
129 |
| -} |
130 |
| -``` |
| 138 | +...then the data may be accessible by the _next_ user. Context solves this problem because it is not shared between requests. |
0 commit comments