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

Sharing State Across Components

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  5
some-alt