Context: setContext and getContext
Context is a way to pass a value from a component to all its descendants, at any depth, without threading it through the props of every intermediate component. Unlike a .svelte.js module, context belongs to a particular component tree, so it is safe during server rendering.
Setting a value
The parent puts a value in with setContext(key, value) from the svelte module:
<!-- src/routes/+page.svelte -->
<script>
import { setContext } from 'svelte';
import TodoCounter from '$lib/components/TodoCounter.svelte';
const todoStore = $state({
items: [
{ id: 1, text: 'Buy bread', done: false },
{ id: 2, text: 'Call Oleg', done: true }
]
});
setContext('todos', todoStore);
</script>
<h1>My tasks <TodoCounter /></h1>The key is any string or symbol. The value is a $state object so that descendants see its changes.
Getting the value
Any nested component reads the value with getContext and the same key:
<!-- src/lib/components/TodoCounter.svelte -->
<script>
import { getContext } from 'svelte';
const todoStore = getContext('todos');
let remaining = $derived(todoStore.items.filter((t) => !t.done).length);
</script>
<span>Left: {remaining}</span>The heading shows "Left: 1". TodoCounter receives no props: the data came through context.
When to call them
setContext and getContext are called only while the component is being created — at the top of the <script> block. In a click handler or in $effect they throw an error. If you need the value in a handler, get it beforehand into a variable, like todoStore above.
Helper functions
To avoid repeating a string key in different files, people usually write a small module:
// src/lib/todo-context.js
import { getContext, setContext } from 'svelte';
const KEY = Symbol('todos');
export function setTodoContext(store) {
setContext(KEY, store);
}
export function getTodoContext() {
return getContext(KEY);
}Now +page.svelte calls setTodoContext(todoStore), and descendants call const todoStore = getTodoContext(). A typo in the key is no longer possible.
Context or a .svelte.js module
.svelte.js module | Context | |
|---|---|---|
| Visibility | the whole app | descendants of one component |
| On the server | shared by all visitors | separate for each request |
| Good for | browser-only state | user data, themes, tree settings |
Common mistake
Putting a plain value into context and expecting updates:
<script>
import { setContext } from 'svelte';
let count = $state(0);
setContext('count', count);
</script>Context receives the number 0 at the moment of the call, and descendants do not see later changes. Pass a $state object (or a function that returns the value) and change its properties.