0
0
Svelteframework~3 mins

Why Context with stores in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to share data effortlessly across your app without endless prop passing!

The Scenario

Imagine you have a big app with many components, and you want to share data like user info or theme settings between them.

You try passing data down through every component manually, like handing a note from one friend to another in a long line.

The Problem

This manual passing is tiring and error-prone. If you add or remove components, you must update all the data passing everywhere.

It's easy to lose track, cause bugs, or write lots of repetitive code.

The Solution

Context with stores lets you share data easily across components without passing it step-by-step.

Stores hold the data, and context makes it available anywhere in the component tree automatically.

Before vs After
Before
let user = {name: 'Anna'};
<Component1 user={user} />
// Component1 passes user to Component2, and so on...
After
import { writable } from 'svelte/store';
import { setContext } from 'svelte';
const user = writable({name: 'Anna'});
setContext('user', user);
// Any component can getContext('user') to access the store directly
What It Enables

You can build flexible apps where data flows smoothly and updates everywhere instantly without messy code.

Real Life Example

Think of a shopping app where the cart info is needed in many places: header, product list, checkout. Context with stores shares the cart data easily so all parts stay in sync.

Key Takeaways

Manual data passing is slow and fragile.

Context with stores shares data globally in a clean way.

It makes your app easier to build and maintain.