setContext lets you share data or functions between components without passing them through every level. It helps components talk to each other easily.
0
0
setContext in Svelte
Introduction
You want to share a theme or style settings across many components.
You have a parent component that fetches data and child components need that data.
You want to share a function like a login or logout handler with nested components.
You want to avoid passing many props through several layers of components.
Syntax
Svelte
import { setContext } from 'svelte'; setContext(key, value);
key is usually a unique string or symbol to identify the context.
value can be any data or function you want to share.
Examples
Share a user object with child components using the key 'user'.
Svelte
import { setContext } from 'svelte'; setContext('user', { name: 'Alice', loggedIn: true });
Share a theme object so children can use the color setting.
Svelte
import { setContext } from 'svelte'; const theme = { color: 'blue' }; setContext('theme', theme);
Sample Program
This parent component shares a user object using setContext. The Child component can get this data without props.
Svelte
<script> import { setContext } from 'svelte'; import Child from './Child.svelte'; const user = { name: 'Bob', loggedIn: true }; setContext('user', user); </script> <h1>Parent Component</h1> <Child />
OutputSuccess
Important Notes
To access the shared data in child components, use getContext(key).
Use symbols as keys to avoid conflicts if many contexts exist.
Context only works downward in the component tree, not upward or sideways.
Summary
setContext shares data/functions from parent to children without props.
Use a unique key to identify the shared context.
Child components use getContext to access the shared data.