Skip to content

Commit 4220873

Browse files
Sync svelte docs (#1887)
sync svelte docs Co-authored-by: svelte-docs-bot[bot] <196124396+svelte-docs-bot[bot]@users.noreply.github.com>
1 parent a765841 commit 4220873

2 files changed

Lines changed: 265 additions & 40 deletions

File tree

apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md

Lines changed: 96 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,66 @@ NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-doc
33
title: Context
44
---
55

6-
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)`...
6+
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').
7+
8+
By creating a `[get, set]` pair of functions with `createContext`, you can set the context in a parent component and get it in a child component:
9+
10+
<!-- codeblock:start {"title":"Context","selected":"context.ts"} -->
11+
```svelte
12+
<!--- file: App.svelte --->
13+
<script>
14+
import Parent from './Parent.svelte';
15+
import Child from './Child.svelte';
16+
</script>
17+
18+
<Parent>
19+
<Child />
20+
</Parent>
21+
```
22+
23+
```svelte
24+
<!--- file: Parent.svelte --->
25+
<script>
26+
import { setUserContext } from './context';
27+
28+
let { children } = $props();
29+
30+
setUserContext({ name: 'world' });
31+
</script>
32+
33+
{@render children()}
34+
```
35+
36+
```svelte
37+
<!--- file: Child.svelte --->
38+
<script>
39+
import { getUserContext } from './context';
40+
41+
const user = getUserContext();
42+
</script>
43+
44+
<h1>hello {user.name}, inside Child.svelte</h1>
45+
```
46+
47+
```ts
48+
/// file: context.ts
49+
import { createContext } from 'svelte';
50+
51+
interface User {
52+
name: string;
53+
}
54+
55+
export const [getUserContext, setUserContext] = createContext<User>();
56+
```
57+
<!-- codeblock:end -->
58+
59+
> [!NOTE] `createContext` was added in version 5.40. If you are using an earlier version of Svelte, you must use `setContext` and `getContext` instead.
60+
61+
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) as shown above.
62+
63+
## `setContext` and `getContext`
64+
65+
As an alternative to `createContext`, you can use `setContext` and `getContext` directly. The parent component sets context with `setContext(key, value)`...
766

867
```svelte
968
<!--- file: Parent.svelte --->
@@ -27,32 +86,28 @@ Context allows components to access values owned by parent components without pa
2786
<h1>{message}, inside Child.svelte</h1>
2887
```
2988

30-
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=)):
31-
32-
```svelte
33-
<Parent>
34-
<Child />
35-
</Parent>
36-
```
37-
3889
The key (`'my-context'`, in the example above) and the context itself can be any JavaScript value.
3990

91+
> [!NOTE] `createContext` is preferred since it provides better type safety and makes it unnecessary to use keys.
92+
4093
In addition to [`setContext`](svelte#setContext) and [`getContext`](svelte#getContext), Svelte exposes [`hasContext`](svelte#hasContext) and [`getAllContexts`](svelte#getAllContexts) functions.
4194

4295
## Using context with state
4396

44-
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=))...
97+
You can store reactive state in context...
4598

99+
<!-- codeblock:start {"title":"Context with state"} -->
46100
```svelte
101+
<!--- file: App.svelte --->
47102
<script>
48-
import { setContext } from 'svelte';
103+
import { setCounter } from './context.ts';
49104
import Child from './Child.svelte';
50105
51106
let counter = $state({
52107
count: 0
53108
});
54109
55-
setContext('counter', counter);
110+
setCounter(counter);
56111
</script>
57112
58113
<button onclick={() => counter.count += 1}>
@@ -62,12 +117,39 @@ You can store reactive state in context ([demo](/playground/untitled#H4sIAAAAAAA
62117
<Child />
63118
<Child />
64119
<Child />
120+
121+
<button onclick={() => counter.count = 0}>
122+
reset
123+
</button>
124+
```
125+
126+
```svelte
127+
<!--- file: Child.svelte --->
128+
<script>
129+
import { getCounter } from './context.ts';
130+
131+
const counter = getCounter();
132+
</script>
133+
134+
<p>{counter.count}</p>
135+
```
136+
137+
```ts
138+
/// file: context.ts
139+
import { createContext } from 'svelte';
140+
141+
interface Counter {
142+
count: number;
143+
}
144+
145+
export const [getCounter, setCounter] = createContext<Counter>();
65146
```
147+
<!-- codeblock:end -->
66148

67149
...though note that if you _reassign_ `counter` instead of updating it, you will 'break the link' — in other words instead of this...
68150

69151
```svelte
70-
<button onclick={() => counter = { count: 0 }}>
152+
<button onclick={() => counter = { count: 0 } }>
71153
reset
72154
</button>
73155
```
@@ -82,21 +164,7 @@ You can store reactive state in context ([demo](/playground/untitled#H4sIAAAAAAA
82164

83165
Svelte will warn you if you get it wrong.
84166

85-
## Type-safe context
86-
87-
As an alternative to using `setContext` and `getContext` directly, you can use them via `createContext`. This gives you type safety and makes it unnecessary to use a key:
88-
89-
```ts
90-
/// file: context.ts
91-
// @filename: ambient.d.ts
92-
interface User {}
93-
94-
// @filename: index.ts
95-
// ---cut---
96-
import { createContext } from 'svelte';
97-
98-
export const [getUserContext, setUserContext] = createContext<User>();
99-
```
167+
## Component testing
100168

101169
When writing [component tests](testing#Unit-and-component-tests-with-Vitest-Component-testing), it can be useful to create a wrapper component that sets the context in order to check the behaviour of a component that uses it. As of version 5.49, you can do this sort of thing:
102170

0 commit comments

Comments
 (0)