Understanding Stores
Pyyhkäise näyttääksesi valikon
As applications grow larger, multiple components often need access to the same data. Passing props through many layers of components can quickly become difficult to manage.
Svelte solves this problem using stores.
What Are Stores?
Stores are special objects used to share reactive data across different components.
Instead of keeping all state inside a single component, stores allow multiple parts of the application to access and update the same data.
This makes state management much easier in larger applications.
Why Shared State Matters
Imagine a shopping cart in an online store. Multiple components may need access to the cart data at the same time:
- A product card may add items;
- A cart icon may display the item count;
- A checkout page may show the full cart contents.
Without shared state management, passing data between many components becomes difficult and repetitive.
Stores help centralize this data.
Creating Your First Store
Create a new folder called stores inside the src directory.
Then create a file called counterStore.js:
import { writable } from 'svelte/store';
export const count = writable(0);
The writable() function creates a reactive store with an initial value.
Using the Store
Open App.svelte and import the store:
<script>
import { count } from './stores/counterStore.js';
</script>
<h2>Count: {$count}</h2>
<button on:click={() => $count += 1}>
Increase
</button>
The $count syntax automatically subscribes to the store and keeps the interface updated when the value changes.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme