Svelte Stores

A store holds a piece of data that several components can share and update together. Stores solve the problem of passing the same value through many layers of props just to reach a distant component.

Why Stores Matter

Passing a value from a top-level component down through five layers of children, only for the value to matter at the bottom layer, wastes effort and clutters every layer in between. A store gives every component direct access to shared data, skipping the long chain entirely.

Creating A Writable Store

<!-- store.js -->
import { writable } from "svelte/store";

export const cartCount = writable(0);

This file creates a store named cartCount, starting at a value of zero. Any component in the project can import this store and read or change its value.

Using A Store Inside A Component

<!-- Cart.svelte -->
<script>
  import { cartCount } from "./store.js";
</script>

<p>Items in cart: {$cartCount}</p>

The dollar sign placed before cartCount tells Svelte to read the store's current value automatically, without writing separate code to subscribe and unsubscribe.

Store Sharing Diagram

                store.js
                cartCount = 0
                    |
      --------------------------------
      |               |               |
      v               v               v
Header.svelte     Cart.svelte     Checkout.svelte
Shows count        Shows count      Shows count

Three separate components read from the exact same store, and updating the value in one place refreshes the count shown in all three at once.

Updating A Store's Value

<script>
  import { cartCount } from "./store.js";

  function addItem() {
    cartCount.update(count => count + 1);
  }
</script>

<button on:click={addItem}>Add To Cart</button>

The update method takes the current value, calculates a new value from it, and stores the result. Every component reading cartCount refreshes immediately after this change.

Setting A Store's Value Directly

<script>
  import { cartCount } from "./store.js";

  function resetCart() {
    cartCount.set(0);
  }
</script>

<button on:click={resetCart}>Clear Cart</button>

The set method replaces the store's value directly, useful when you already know the exact new value rather than calculating it from the old one.

Derived Stores

import { writable, derived } from "svelte/store";

export const price = writable(100);
export const quantity = writable(2);

export const total = derived([price, quantity], ([$price, $quantity]) => $price * $quantity);

A derived store calculates its value from one or more other stores, updating automatically whenever any of its source stores change.

Manually Subscribing To A Store

The dollar sign shortcut works only inside a Svelte component's markup and script. Plain JavaScript files, such as a helper file, need a manual subscription instead.

import { cartCount } from "./store.js";

const unsubscribe = cartCount.subscribe(value => {
  console.log("Cart count is now", value);
});

The subscribe method runs its callback immediately with the current value, then runs it again every time the store changes. Calling the returned unsubscribe function stops this listening, useful for cleanup outside a component's automatic handling.

Key Points

  • A store holds shared data accessible from any component in a project
  • The dollar sign prefix reads a store's current value automatically inside a component
  • The update method changes a store based on its current value
  • The set method replaces a store's value directly

Leave a Comment

Your email address will not be published. Required fields are marked *