javascript / intermediate
Snippet
Dependency Injection with the Context API
The Context API provides a way to share data through the component tree without 'prop drilling'. Unlike stores that are globally accessible, context is scoped to the component where it is set and its descendants, making it ideal for theme or user-session management within specific UI branches.
snippet.js
1
2
3
4
5
6
7
8
9
10
<script>import { setContext } from 'svelte';import { writable } from 'svelte/store';// Define a store to be sharedlet user = writable({ name: 'Markus', role: 'editor' });// Make the store available to all childrensetContext('userProfile', user);</script>
svelte
Breakdown
1
import { setContext } from 'svelte';
Imports the function used to associate a key with a value in the current component context.
2
setContext('userProfile', user);
Binds the string key 'userProfile' to the 'user' store for all child components to access via getContext.