How to Use Context in Svelte: Simple Guide with Examples
In Svelte, you use
setContext to provide data in a parent component and getContext to access that data in child components. This allows components to share information without passing props through every level.Syntax
Use setContext(key, value) in a parent component to store data. Use getContext(key) in a child component to retrieve that data. The key is usually a string or a Symbol to identify the context.
svelte
<script> import { setContext, getContext } from 'svelte'; // Parent.svelte setContext('myKey', 'some value'); // Child.svelte const value = getContext('myKey'); </script>
Example
This example shows a parent component setting a context value and a child component reading and displaying it.
svelte
<!-- Parent.svelte --> <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; setContext('user', { name: 'Alice', age: 30 }); </script> <main> <h1>Parent Component</h1> <Child /> </main> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; const user = getContext('user'); </script> <p>User name: {user.name}</p> <p>User age: {user.age}</p>
Output
Parent Component
User name: Alice
User age: 30
Common Pitfalls
- Trying to use
getContextin a component that is not a descendant of the component that calledsetContextwill returnundefined. - Using the same
keyin multiple places can cause conflicts; use unique keys like Symbols. - Context is not reactive by default; if the context value changes, children won’t update unless you use stores.
svelte
<!-- Wrong: getContext used outside parent hierarchy --> <script> import { getContext } from 'svelte'; const value = getContext('missingKey'); // returns undefined </script> <!-- Right: Use unique Symbol keys --> <script> import { setContext, getContext } from 'svelte'; const key = Symbol('uniqueKey'); setContext(key, 'value'); const value = getContext(key); </script>
Quick Reference
| Function | Purpose | Usage |
|---|---|---|
| setContext | Stores data in a parent component | setContext(key, value) |
| getContext | Retrieves data in a child component | const value = getContext(key) |
| key | Identifier for context data | Usually a string or Symbol |
Key Takeaways
Use setContext in a parent to share data with descendants.
Use getContext in child components to access shared data.
Keys should be unique, preferably Symbols, to avoid conflicts.
Context is not reactive by default; use stores for reactive data.
getContext returns undefined if used outside the provider hierarchy.