0
0
Svelteframework~30 mins

Context API vs stores in Svelte - Hands-On Comparison

Choose your learning style9 modes available
Using Context API and Stores in Svelte
📖 Scenario: You are building a simple Svelte app that shares a user's name across components. You want to learn how to share data using both the Context API and Svelte stores.
🎯 Goal: Build a Svelte app that sets a user's name in a parent component and shares it with a child component using Context API and a store. You will create the data, configure the context and store, use them in child components, and complete the app structure.
📋 What You'll Learn
Create a writable store called userName with initial value "Alice"
Create a context key called userKey with value Symbol()
Set the context with setContext(userKey, userName) in the parent component
Use getContext(userKey) in the child component to access the store
Subscribe to the store in the child component to display the user's name
Use the store directly in another child component to display the user's name
💡 Why This Matters
🌍 Real World
Sharing data between components is common in apps. Context API helps pass data deeply without prop drilling. Stores provide reactive global state. Knowing both helps build clean, maintainable Svelte apps.
💼 Career
Understanding Svelte's Context API and stores is important for frontend developers working with Svelte. It helps manage state efficiently and build scalable component architectures.
Progress0 / 4 steps
1
Create the userName store
In a file called stores.js, import writable from svelte/store and create a writable store called userName with the initial value "Alice".
Svelte
Hint

Use writable to create a store that holds the user's name.

2
Create the context key and set context in parent
In Parent.svelte, import setContext from svelte and userName from ./stores.js. Create a constant userKey with Symbol(). Use setContext(userKey, userName) inside the script to provide the store via context.
Svelte
Hint

Use Symbol() to create a unique key and setContext to share the store.

3
Use getContext to access store in Child component
In Child.svelte, import getContext from svelte. Use const userKey = Symbol() and then get the store with const userName = getContext(userKey). Subscribe to userName store and display the current value inside a <p> tag.
Svelte
Hint

Use getContext with the same key to access the store and subscribe to it.

4
Use the store directly in another Child component
In ChildStore.svelte, import userName from ./stores.js. Use the $userName auto-subscription syntax to display the user's name inside a <p> tag.
Svelte
Hint

Use the $ prefix to auto-subscribe to the store in the template.