Svelte logo

Svelte by Example: Derived Stores

Derived stores calculate values from other stores. They're useful when you want to subscribe to a slice of state, or a transformed representation of state in multiple places. For rune-based state, use $derived instead.

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

Svelte exposes a derived function to create derived stores.

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

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

export const todos = writable([
  { task: 'Walk dog', completed: false },
]);


export const completedTodos = derived(
  todos,
  (items) => items.filter((todo) => todo.completed),
);

Like any module-level store, this is shared. Create stores per component tree for per-user state when rendering on the server.

Read a derived store with $ too. The count updates when the todos store changes.

TodoCount.svelte
<script>
  import { completedTodos } from './stores.js';
</script>


<p>{$completedTodos.length} completed todos</p>