Context and stores help share data in Svelte apps without passing props everywhere. Choosing between them makes your app simpler and easier to manage.
0
0
Context vs stores decision in Svelte
Introduction
You want to share data only between a few related components deep in the tree.
You need global data accessible by many components across your app.
You want reactive data that updates UI automatically when changed.
You want to avoid prop drilling through many layers of components.
You want to keep some data private to a part of your app.
Syntax
Svelte
/* Context API */ import { setContext, getContext } from 'svelte'; // In parent component setContext('key', value); // In child component const value = getContext('key'); /* Store API */ import { writable } from 'svelte/store'; const count = writable(0); // In any component count.subscribe(value => { /* react to value */ }); count.set(5);
Context is for passing data down the component tree without props.
Stores hold reactive data accessible anywhere by importing them.
Examples
Context shares the user object only with children components.
Svelte
// Using context // Parent.svelte <script> import { setContext } from 'svelte'; setContext('user', { name: 'Anna' }); </script> // Child.svelte <script> import { getContext } from 'svelte'; const user = getContext('user'); console.log(user.name); </script>
Store shares reactive count value globally across components.
Svelte
// Using store // store.js import { writable } from 'svelte/store'; export const count = writable(0); // AnyComponent.svelte <script> import { count } from './store.js'; count.subscribe(value => console.log(value)); count.set(10); </script>
Sample Program
This example shows how context passes the user object from Parent to Child without props.
Svelte
<!-- Parent.svelte --> <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; const user = { name: 'Sam' }; setContext('user', user); </script> <h1>Parent Component</h1> <Child /> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; const user = getContext('user'); </script> <p>Hello, {user.name}!</p>
OutputSuccess
Important Notes
Use context when data is only needed by child components in a specific part of the tree.
Use stores for app-wide reactive data shared by many components.
Stores can be updated and subscribed to anywhere by importing them.
Summary
Context shares data down the component tree without props.
Stores hold reactive data accessible globally by importing.
Choose context for local sharing, stores for global reactive data.