0 day streak
javascript / intermediate
Snippet

Avoiding Prop Drilling with Context API

The Context API allows you to share data through the component tree without passing props through every intermediate level (prop drilling). 'setContext' is used in an ancestor, and 'getContext' retrieves the data in any descendant.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
// Parent.svelte
<script>
import { setContext } from 'svelte';
let theme = 'dark';
setContext('app-theme', { theme });
</script>
// DeepChild.svelte
<script>
import { getContext } from 'svelte';
const { theme } = getContext('app-theme');
</script>
<div class="{theme}">Themed Content</div>
svelte
Breakdown
1
setContext('app-theme', { theme });
Associates a specific key with a value for all nested components.
2
const { theme } = getContext('app-theme');
Retrieves the value associated with the key from the nearest provider.