0
0
Svelteframework~30 mins

Context key patterns in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Context Key Patterns in Svelte
📖 Scenario: You are building a simple Svelte app where a parent component shares a theme color with its child components using context keys.
🎯 Goal: Learn how to create and use context keys in Svelte to pass data from a parent component to child components without props.
📋 What You'll Learn
Create a unique context key using Symbol()
Set context in the parent component using setContext
Get context in the child component using getContext
Display the shared theme color in the child component
💡 Why This Matters
🌍 Real World
Context keys let you share data like themes, user info, or settings between components without passing props through many layers.
💼 Career
Understanding context keys is important for building scalable Svelte apps where components need to share data cleanly and efficiently.
Progress0 / 4 steps
1
Create a unique context key
In a new Svelte component file, create a constant called themeKey and assign it the value Symbol('theme').
Svelte
Hint

Use const themeKey = Symbol('theme') to create a unique key for context.

2
Set context in the parent component
Import setContext from 'svelte'. Then use setContext(themeKey, 'darkblue') to share the theme color 'darkblue' using the themeKey.
Svelte
Hint

Remember to import setContext and call it with the key and value.

3
Get context in the child component
In a child Svelte component, import getContext from 'svelte'. Then create a constant called theme and assign it the value returned by getContext(themeKey).
Svelte
Hint

Use getContext(themeKey) to access the shared theme value.

4
Display the theme color in the child component
In the child component's markup, add a <div> that shows the text Theme color: {theme}. This will display the shared theme color from context.
Svelte
Hint

Use a <div> with {theme} inside to show the color.