0
0
Svelteframework~30 mins

Context with stores in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Context with stores in Svelte
📖 Scenario: You are building a simple Svelte app where multiple components need to share and update a counter value. Instead of passing props down many levels, you will use Svelte's context with stores to share the counter state easily.
🎯 Goal: Create a Svelte app with a store holding a counter value. Provide this store via context in a parent component. Then, in a child component, access the store from context and display and update the counter.
📋 What You'll Learn
Create a writable store called counter with initial value 0
Set the counter store in context using setContext with key 'counter'
In a child component, get the counter store from context using getContext
Display the current counter value and add a button to increment it
💡 Why This Matters
🌍 Real World
Sharing state like counters, user info, or settings across many components without prop drilling.
💼 Career
Understanding context and stores is key for building scalable Svelte apps and collaborating on frontend projects.
Progress0 / 4 steps
1
Create the counter store
In a new Svelte component, import writable from 'svelte/store' and create a writable store called counter with initial value 0.
Svelte
Hint

Use writable(0) to create a store starting at zero.

2
Set the counter store in context
In the parent Svelte component, import setContext from 'svelte' and the counter store. Use setContext with key 'counter' to provide the counter store to child components.
Svelte
Hint

Use setContext('counter', counter) to share the store.

3
Get the counter store from context in child
In a child Svelte component, import getContext from 'svelte'. Use getContext('counter') to get the counter store from context and assign it to a variable called counter.
Svelte
Hint

Use const counter = getContext('counter') to access the store.

4
Display and update the counter in child component
In the child component, use the $counter store value to display the current count inside a <p> tag. Add a button with text Increment that increases the counter by 1 when clicked using counter.update(n => n + 1).
Svelte
Hint

Use {$counter} to show the current value and on:click to handle button clicks.