0
0
Svelteframework~3 mins

Context vs stores decision in Svelte - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how to effortlessly share data in Svelte without tangled props or confusing updates!

The Scenario

Imagine you have a Svelte app where many components need to share data like user info or theme settings. You try passing props down through many layers or manually updating each component.

The Problem

Passing props through many layers is tiring and error-prone. If you update data, you must manually notify every component. This leads to messy code and bugs.

The Solution

Svelte's context and stores let you share data easily. Context passes data down the tree without props, while stores provide reactive shared state accessible anywhere.

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';
export const user = writable({name: 'Anna'});
// Any component can import and subscribe to the user store
What It Enables

You can share and react to data changes smoothly across your app without messy prop chains or manual updates.

Real Life Example

In a shopping app, the cart data is shared across header, product list, and checkout components. Using stores or context keeps all parts in sync instantly.

Key Takeaways

Passing data manually through props is slow and error-prone.

Context shares data down the component tree without props.

Stores provide reactive shared state accessible anywhere.