Learn Svelte Stores

A store is a container for a value in its own file that many components can read and change. writable([]) from "svelte/store" makes a store with three…

In a family WhatsApp group, one person posts a message and every member gets the notification at the same time, without phoning each other. Svelte has something similar for data, called a store: a container for a value that lives outside any component. Many components can read it and change it. Every component that subscribes (asks to be told about changes) hears about each change. If you've used Context in React or Pinia in Vue, the role is similar.

Picture a group called "Mrs. Sri's Stall Cart". The waiter posts a new order in the group, and the cashier and the cook get the notification at the same time. A member who goes home leaves the group, so their phone stops buzzing. In code, the group is the store. Writing to the store is posting a message, subscribing is joining the group, and unsubscribing (stopping the subscription) is leaving it.

Why a store

At Mrs. Sri's stall, MenuList.svelte has the Add buttons, and Header.svelte shows how many items are in the cart. Both are children of App, so they can't pass props to each other (props only go from a parent to its child). You could keep cart in App, then pass it down to both children through props. But the more components need it, the longer that chain of passing gets. A store keeps the value in its own file, and any component simply imports it.

writable: making a store

This cart store is written in a file called stores.js:

// stores.js
import { writable } from "svelte/store"

export const cart = writable([])
Method What it does
subscribe(fn) calls fn now with the current value, then on every change. Returns a function that stops the subscription.
set(value) replaces the value with a new one
update(fn) computes the new value from the old one: update((c) => [...c, "Iced Tea"])

The $ sign: automatic subscription

In a .svelte file, put $ in front of a store's name to read its value. These two components import the same cart store:

<!-- MenuList.svelte -->
<script>
  import { cart } from "./stores.js"
  const menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"]
</script>

{#each menu as name}
  <button onclick={() => cart.update((c) => [...c, name])}>Add {name}</button>
{/each}
<button onclick={() => cart.set([])}>Clear</button>
<!-- Header.svelte -->
<script>
  import { cart } from "./stores.js"
</script>

<p>Items in cart: {$cart.length}</p>
Event cart holds Header
Start [] Items in cart: 0
Click Add Fried Rice ["Fried Rice"] Items in cart: 1
Click Add Iced Tea ["Fried Rice", "Iced Tea"] Items in cart: 2
Click Clear [] Items in cart: 0

Manual subscribe and unsubscribe

Sometimes you need the value inside <script>, or in a .js file. Call subscribe yourself, and keep the function it returns. This is a Header that subscribes by itself:

<script>
  import { onDestroy } from "svelte"
  import { cart } from "./stores.js"

  let items = $state([])
  const unsubscribe = cart.subscribe((c) => {
    items = c
  })
  onDestroy(unsubscribe)
</script>

<p>Items in cart: {items.length}</p>

subscribe runs its function now, then every time the cart changes, so items always matches the cart. If onDestroy(unsubscribe) is forgotten, a Header that was removed stays registered as a subscriber, and its callback keeps being called whenever the cart changes. Mount Header, remove it, mount it again, remove it, then mount it a third time. The store now has three subscribers, and two of them are components that no longer exist. It's the same leak as the interval in the Svelte Lifecycle lesson. $cart doesn't have this problem.

readable: a store you can only read

readable(initialValue, start) makes a store with no set or update that can be called from outside. Only the start function inside it changes the value, through the set it receives:

import { readable } from "svelte/store"

export const time = readable(new Date().toLocaleTimeString("en-GB"), (set) => {
  const timer = setInterval(() => set(new Date().toLocaleTimeString("en-GB")), 1000)
  return () => clearInterval(timer)
})

Exercises: count and name

In the first exercise, you make a counter with a store:

<script>
  import { writable } from "svelte/store"

  const count = writable(0)
</script>

<p>Count: {$count}</p>
<button onclick={() => $count += 1}>+1</button>

It starts as Count: 0. One click makes it Count: 1, and two clicks make it Count: 2. In the second exercise, you make a greeting that follows what is typed in a text field:

<script>
  import { writable } from "svelte/store"

  const name = writable("World")
</script>

<input bind:value={$name} />
<h1>Hello, {$name}!</h1>

It starts as Hello, World!. Type Sinta, and the heading becomes Hello, Sinta!.

Shared state in a .svelte.js file

In Svelte 5, state that many components use is also often kept in a file ending in .svelte.js, as an exported $state. Here is the same cart, with no store:

// cart.svelte.js
export const cart = $state([])
<!-- MenuList.svelte -->
<script>
  import { cart } from "./cart.svelte.js"
</script>

<button onclick={() => cart.push("Iced Tea")}>Add Iced Tea</button>
<p>Items in cart: {cart.length}</p>

⚠️ Misusing the dollar sign, and subscriptions never dropped

TL;DR: A store is a container for a value in its own file that many components can read and change. writable([]) from "svelte/store" makes a store with three methods: subscribe (asks to be told about every change), set and update. In a .svelte file, {$cart} reads the value of the cart store: the component subscribes when it is created and stops when it is removed. Without $, it shows [object Object]. $count += 1 and bind:value={$name} write to the store. A subscribe you call yourself must be paired with unsubscribe (stopping the subscription) in onDestroy. If not, a removed component keeps hearing changes. A readable store can't be changed from outside: the function inside it sets the value. In Svelte 5, shared state is also often written as a $state exported from a .svelte.js file, and read with no $. The exercises: const count = writable(0) with <p>Count: {$count}</p> and a +1 button that makes it Count: 1 then Count: 2, and const name = writable("World") with <input bind:value={$name} /> and <h1>Hello, {$name}!</h1>.

⚡ writable: a container in its own file

Write:

// stores.js
import { writable } from "svelte/store"

export const cart = writable([])

Meaning: A store is a container for a value outside any component. Many components can import it, read it and change it. writable is imported from "svelte/store" and makes a store you can write to. This cart store starts as an empty array, and has three methods: subscribe (asks to be told about every change), set (replaces the value) and update (computes the new value from the old one).

⚡ The $ sign subscribes

Write:

<p>Items in cart: {$cart.length}</p>
Guess first: you write {cart} without the $. What shows?

[object Object]. What's read is the store itself, the object holding those three methods, not its value.

Meaning: A $ in front of a store's name reads its value, so $cart is the array of items in the cart. The component subscribes by itself when it's created, and stops by itself when it's removed. Through $ you can also write to a store: $count += 1 adds 1 to the count store.

⚡ A readable can't be changed from outside

Write:

export const time = readable(new Date().toLocaleTimeString("en-GB"), (set) => {
  const timer = setInterval(() => set(new Date().toLocaleTimeString("en-GB")), 1000)
  return () => clearInterval(timer)
})

Meaning: readable (also from "svelte/store") makes a store with no set or update to call from outside. Only the function inside it changes the value: here an interval calls set every second with the new time, and the function it returns stops that interval when nothing subscribes any more. A component that tries time.set("07:00") gets a TypeError. That's the difference from writable.

What you will learn