How to Use setContext in Svelte: Simple Guide with Examples
In Svelte, use
setContext inside a parent component to provide data or functions that child components can access with getContext. This allows sharing values without passing props through every level of the component tree.Syntax
The setContext function takes two arguments: a unique key and a value to share. The key is usually a string or a Symbol to avoid conflicts. Child components use the same key with getContext to access the value.
svelte
import { setContext } from 'svelte'; setContext(key, value);
Example
This example shows a parent component setting a context value, and a child component accessing it without props.
svelte
<!-- Parent.svelte --> <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; const user = { name: 'Alice', role: 'admin' }; const key = 'user'; setContext(key, user); </script> <main> <h1>Parent Component</h1> <Child /> </main> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; const key = 'user'; const user = getContext(key); </script> <p>User name: {user.name}</p> <p>User role: {user.role}</p>
Output
Parent Component
User name: Alice
User role: admin
Common Pitfalls
- Using the wrong key: The key must be exactly the same in
setContextandgetContext. Using different strings or symbols will causegetContextto returnundefined. - Calling
setContextoutside component setup: It must be called inside the component script, not in event handlers or lifecycle functions. - Expecting reactivity: Values passed via context are not reactive by default. Use stores if you want reactive shared data.
svelte
<!-- Wrong key example --> <script> import { setContext } from 'svelte'; setContext('user', { name: 'Bob' }); </script> <!-- Child tries to get with different key --> <script> import { getContext } from 'svelte'; const user = getContext('User'); // different case console.log(user); // undefined </script>
Output
undefined
Quick Reference
setContext(key, value): Provide a value to child components.
getContext(key): Retrieve the value in child components.
Key: Use a unique string or Symbol.
Use case: Share data/functions without prop drilling.
Note: For reactive data, use Svelte stores in context.
Key Takeaways
Use setContext in a parent component to share data with descendants without props.
The key used in setContext and getContext must match exactly to access the value.
setContext must be called inside the component script, not in event handlers.
Context values are not reactive by default; use stores for reactive shared data.
Use unique keys (strings or Symbols) to avoid conflicts in context sharing.