Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Sharing State Across Components | Stores and Shared State
Introduction to Svelte

Sharing State Across Components

Glissez pour afficher le 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.

question mark

What is the main advantage of using shared state with stores in Svelte?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 5

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 4. Chapitre 5
some-alt