Svelte logo

Svelte by Example: Derived Stores

Derived stores can be created to derive values from other stores. Derived stores are useful when you want to subscribe to a slice of state, or a transformed representation of state in multiple places.

In this example, we'll create a derived store from our todos store that only returns completed todos.

Svelte exposes a derived function to create derived stores.

The first argument in derived is an existing store. The second is a function that calculates the derived data from the current store value.

stores.js
import { writable, derived } from 'svelte/store';

export const todos = writable([]);

export const completedTodos = derived(
  todos,
  ($todos) => {
    return $todos.filter((todo) => todo.completed),
  },
);