Svelte logo

Svelte by Example: Custom Stores

The only requirement for an object to be a store is to expose a subscribe function. We can use Svelte's built-in store helpers to create custom stores. Custom stores are useful to encapsulate data and expose specific functions to manage state.

In this example, we'll create a custom todos store.

You can use a writable Svelte store as a starting point.

Functions the custom store should expose are implemented.

The functions and subscribe are exported. A Svelte store must export a subscribe function.

The store can be destructured for easy method access in the template.

The store can be used in the template like any other store, and $ calls subscribe.

import { writable } from 'svelte/store';

const { update, set, subscribe } = writable([]);

function addTodo() {
  update((todos) => {
      task: 'Read newspaper',
      completed: false,

function checkTodo(index, completed) {
  update((todos) => {
    return, i) => {
      return index === i
        ? { ...todo, completed }
        : todo;

export {
  import Todo from './Todo.svelte';
  import AddTodo from './AddTodo.svelte';
  import { todos } from './stores.js';

  const { addTodo, checkTodo } = todos;

  addTodo('Walk dog');

{#each $todos as todo, index}
    on:checked={(event) => {
      checkTodo(index, event.detail.checked);

<AddTodo on:add={addTodo} />