Sharing State Across Components
Scorri per mostrare il menu
One of the biggest advantages of stores is the ability to share the same reactive state across multiple components. Instead of passing data through many layers of props, components can access shared stores directly.
This makes larger frontend applications easier to organize and maintain.
Why Shared State Matters
In real applications, many components often depend on the same data.
For example, an online store may have:
- A product list component;
- A shopping cart icon;
- A checkout section.
All of these components may need access to the same cart data.
Without shared state management, passing props between many components can quickly become difficult and repetitive.
Creating Shared State
Inside the stores folder, create a file called cartStore.js.
import { writable } from 'svelte/store';
export const cartCount = writable(0);
This store can now be accessed from any component in the application.
Updating State from One Component
Create a file called AddToCartButton.svelte.
<script>
import { cartCount } from './stores/cartStore.js';
</script>
<button on:click={() => $cartCount += 1}>
Add To Cart
</button>
When the button is clicked, the shared store value updates.
Reading State in Another Component
Now create CartStatus.svelte.
<script>
import { cartCount } from './stores/cartStore.js';
</script>
<h2>Cart Items: {$cartCount}</h2>
Even though this component never directly changes the value, it still receives automatic updates from the shared store.
Using Both Components Together
Inside App.svelte:
<script>
import AddToCartButton from './AddToCartButton.svelte';
import CartStatus from './CartStatus.svelte';
</script>
<CartStatus />
<AddToCartButton />
Now both components stay synchronized through the shared store.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione