Stores help keep data in one place so many parts of your app can use it easily. This makes your app simpler and faster to update.
0
0
Why stores manage shared state in Svelte
Introduction
When multiple components need to see or change the same data
When you want to keep data updated everywhere without extra work
When you want to avoid passing data through many layers of components
When you want a simple way to share user settings or app status
When you want to react to data changes automatically in your UI
Syntax
Svelte
import { writable } from 'svelte/store'; const count = writable(0); // To update: count.set(5); // To subscribe: const unsubscribe = count.subscribe(value => { console.log(value); });
writable creates a store you can read and write.
Use subscribe to react to changes in the store.
Examples
Create a store holding a name string.
Svelte
import { writable } from 'svelte/store'; const name = writable('Alice');
Change the store value to 'Bob'.
Svelte
name.set('Bob');
Listen for changes and log the current name.
Svelte
const unsubscribe = name.subscribe(value => { console.log('Name is', value); });
Sample Program
This Svelte component uses a store to keep a count number. Clicking the button increases the count. The count is shared through the store and shown in the paragraph.
Svelte
<script> import { writable } from 'svelte/store'; // Create a store to hold a number export const count = writable(0); // Function to increase count function increment() { count.update(n => n + 1); } </script> <button on:click={increment} aria-label="Increase count">Increase</button> <p>Count: {$count}</p>
OutputSuccess
Important Notes
Stores automatically update all parts of your app that use them.
Use $storeName syntax in Svelte components to read store values reactively.
Stores help avoid complex data passing between components.
Summary
Stores keep shared data in one place for easy access.
They update all parts of the app automatically when data changes.
Using stores makes your app simpler and easier to maintain.