Context with stores lets you share data easily between components without passing props everywhere.
Context with stores in Svelte
import { writable } from 'svelte/store'; import { setContext, getContext } from 'svelte'; // Create a store const count = writable(0); // Provide context in a parent component setContext('key', count); // Access context in a child component const count = getContext('key');
setContext shares data down the component tree.
getContext retrieves that data in child components.
import { writable } from 'svelte/store'; import { setContext } from 'svelte'; const theme = writable('light'); setContext('theme', theme);
import { getContext } from 'svelte'; const theme = getContext('theme'); $: console.log($theme);
import { writable } from 'svelte/store'; import { setContext, getContext } from 'svelte'; // Parent.svelte const user = writable({ name: 'Anna' }); setContext('user', user); // Child.svelte const user = getContext('user'); $: console.log($user.name);
The parent component creates a count store and shares it via context. It also has a button to increase the count. The child component gets the count store from context and shows its current value. When you click the button, the count updates and the child shows the new value.
<!-- Parent.svelte --> <script> import { writable } from 'svelte/store'; import { setContext } from 'svelte'; const count = writable(0); setContext('count', count); function increment() { count.update(n => n + 1); } </script> <button on:click={increment}>Increment</button> <slot /> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; const count = getContext('count'); </script> <p>Count value: {$count}</p>
Context only works between parent and child components, not across unrelated components.
Stores in context stay reactive, so changes update all components using them.
Use unique keys for context to avoid conflicts.
Context with stores shares reactive data easily between components.
Use setContext in a parent and getContext in children.
This avoids passing props through many layers.