0
0
Svelteframework~30 mins

Context vs stores decision in Svelte - Hands-On Comparison

Choose your learning style9 modes available
Context vs Stores Decision in Svelte
📖 Scenario: You are building a simple Svelte app that shares a user's theme preference (light or dark) across components.You want to learn when to use context and when to use stores in Svelte for sharing data.
🎯 Goal: Create a Svelte app that sets up a theme preference using context in one component and a store in another. Then decide which method is better for sharing the theme across multiple components.
📋 What You'll Learn
Create a Svelte component that sets a theme value using setContext
Create a Svelte component that creates a writable store for theme
Access the theme value using getContext in a child component
Subscribe to the theme store in another component
Add a button to toggle the theme between 'light' and 'dark'
Explain which method is better for global theme sharing
💡 Why This Matters
🌍 Real World
Sharing theme or user preferences across many components in a Svelte app is common. Choosing between context and stores affects app design and reactivity.
💼 Career
Understanding when to use context vs stores helps you build scalable Svelte apps and collaborate with teams on state management.
Progress0 / 4 steps
1
Set up theme context in a parent component
In a Svelte component called ThemeContextProvider.svelte, import setContext from 'svelte'. Create a variable theme set to the string 'light'. Use setContext with the key 'theme' and the value theme. This will share the theme using context.
Svelte
Hint

Use setContext('theme', theme) to share the theme string.

2
Create a writable store for theme
In a new file called themeStore.js, import writable from 'svelte/store'. Create a writable store named themeStore with initial value 'light'. Export themeStore.
Svelte
Hint

Use writable('light') to create the store.

3
Access theme from context in a child component
In a Svelte component called ThemeConsumer.svelte, import getContext from 'svelte'. Use getContext with the key 'theme' to get the theme value into a variable called theme. Display the theme inside a <p> tag.
Svelte
Hint

Use getContext('theme') to access the shared theme.

4
Subscribe to theme store and toggle theme
In a Svelte component called ThemeStoreConsumer.svelte, import themeStore from './themeStore.js'. Use the $themeStore auto-subscription to display the current theme inside a <p> tag. Add a button that toggles the theme between 'light' and 'dark' by calling themeStore.set().
Svelte
Hint

Use $themeStore to auto-subscribe and themeStore.update() to toggle.