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

Sharing State Across Components

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 5

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 4. Kapittel 5
some-alt