javascript / beginner
Snippet
Sharing Data with Context
The Context API provides a way to share data between components without passing it through every level as props, making it ideal for deeply nested trees.
snippet.js
1
2
3
4
5
6
7
import { setContext, getContext } from 'svelte';// In a parent componentsetContext('settings', { theme: 'dark' });// In any descendant componentconst settings = getContext('settings');
svelte
Breakdown
1
setContext('settings', { theme: 'dark' });
Sets a value under a unique key that is available to all children of this component.
2
getContext('settings');
Retrieves the value associated with the key from the nearest parent component's context.