Context key patterns help you share data between components without passing props all the time. It makes your code cleaner and easier to manage.
Context key patterns in Svelte
import { setContext, getContext } from 'svelte'; // In parent component setContext(key, value); // In child component const value = getContext(key);
The key can be any value, but using a Symbol is best to avoid conflicts.
Only components inside the parent can access the context with the same key.
// Using a string key import { setContext, getContext } from 'svelte'; // Parent.svelte setContext('color', 'blue'); // Child.svelte const color = getContext('color');
// Using a Symbol key import { setContext, getContext } from 'svelte'; const THEME = Symbol('theme'); // Parent.svelte setContext(THEME, { background: 'white' }); // Child.svelte const theme = getContext(THEME);
This example shows how to share user data using a Symbol key stored in a separate file. This avoids key mismatches and allows the child component to access the user info correctly.
<!-- Parent.svelte --> <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; import { USER } from './userKey.js'; const user = { name: 'Alice', loggedIn: true }; setContext(USER, user); </script> <h1>Welcome to the app</h1> <Child /> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; import { USER } from './userKey.js'; const user = getContext(USER); </script> <p>User name: {user.name}</p> <p>Logged in: {user.loggedIn ? 'Yes' : 'No'}</p> <!-- userKey.js --> export const USER = Symbol('user');
Always use the same key instance (like a shared Symbol) in both setContext and getContext.
Context only works downward in the component tree, not upward or sideways.
Context is great for global-like data but avoid overusing it for everything.
Context key patterns let you share data easily between components without props.
Use Symbols as keys to avoid conflicts and keep keys unique.
Keep your keys in shared files to use them consistently across components.