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 0Set the
counter store in context using setContext with key 'counter'In a child component, get the
counter store from context using getContextDisplay 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