0 day streak
javascript / expert
Snippet

Dependency Injection with the Context API

The Context API is an expert-level pattern for deep component tree communication without 'prop drilling'. Unlike stores, context is not reactive by default and is bound to the component lifecycle and its descendants. It is ideal for dependency injection, such as providing a database client or theme engine to a large subtree.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
// ParentComponent.svelte
import { setContext } from 'svelte';
const api = {
log: (msg) => console.log(`[Context]: ${msg}`)
};
setContext('app-api', api);
// ChildComponent.svelte
import { getContext } from 'svelte';
const api = getContext('app-api');
api.log('Child calling context!');
svelte
Breakdown
1
setContext(key, value)
Associates an object with a key, accessible to all children of this component.
2
getContext(key)
Retrieves the object from the nearest parent provider. Returns undefined if not found.