Svelte logo

Svelte by Example: Derived State & Effects

Derived state is data calculated from other state. Use $derived for calculations, and $effect for side effects when state changes.

In this example, we'll add a toggle to show or hide completed todos.

We'll continue with our AddTodo and bindable Todo components from the state example.

When todos, a todo's completed property, or showCompleted change, visibleTodos will be updated. When the toggle is off, we only show unfinished todos.

Binding still updates the original todo, even when it's in a filtered list.

Bind a checkbox to the toggle state.

TodoList.svelte
<script>
  import Todo from './Todo.svelte';
  import AddTodo from './AddTodo.svelte';

  let todos = $state([]);
  let showCompleted = $state(false);



  let visibleTodos = $derived(
    showCompleted
      ? todos
      : todos.filter((todo) => !todo.completed)
  );

  function addTodo(todo) {
    todos.push(todo);
  }
</script>

{#each visibleTodos as todo (todo)}
  <Todo
    task={todo.task}

    bind:completed={todo.completed}
  />
{/each}

<label>

  <input type="checkbox" bind:checked={showCompleted}>
  Show completed
</label>

<AddTodo onadd={addTodo} />

Effects

$effect runs after the component mounts, and again when state read synchronously inside it changes. Effects only run in the browser, not during server rendering.

Here, changing the checkbox updates the document title. Use $derived, not an effect, to calculate values for your template.

TodoList.svelte
<script>
  let showCompleted = $state(false);





  $effect(() => {
    document.title = showCompleted
      ? 'All todos'
      : 'Unfinished todos';
  });
</script>

<label>
  <input type="checkbox" bind:checked={showCompleted}>
  Show completed
</label>