What is Store in Svelte: Simple Explanation and Usage
store is a special object that holds reactive data which can be shared across components. It lets components automatically update when the stored data changes, making state management simple and efficient.How It Works
A store in Svelte acts like a shared container for data that many parts of your app can watch and react to. Imagine it as a mailbox where you put a message (data), and anyone subscribed to that mailbox gets notified immediately when the message changes.
When you use a store, components subscribe to it and automatically update their display whenever the store's value changes. This means you don't have to manually tell each component to refresh; Svelte handles it for you behind the scenes.
Stores use a simple contract: they have a subscribe method to listen for changes, and methods like set or update to change the stored value. This keeps your app reactive and your code clean.
Example
This example shows a simple counter using a Svelte writable store. The store holds the count value, and the component updates automatically when the count changes.
import { writable } from 'svelte/store'; // Create a writable store with initial value 0 export const count = writable(0); // In a Svelte component <script> import { count } from './store.js'; function increment() { count.update(n => n + 1); } </script> <button on:click={increment}> Count is {$count} </button>
When to Use
Use stores in Svelte when you need to share reactive data between multiple components without passing props down many levels. They are perfect for global state like user info, theme settings, or counters.
Stores help keep your app organized by centralizing state and reducing the need for complex event handling. For example, if you have a shopping cart that many components need to read and update, a store makes this easy and reactive.
Key Points
- Stores hold reactive data that components can subscribe to.
- They automatically update components when data changes.
- Svelte provides writable, readable, and derived stores for different needs.
- Stores simplify sharing state across components without prop drilling.
- Use stores for global or shared state like user info, settings, or counters.