Svelte logo

Svelte by Example: Reactive Statements

Reactive statements can be used to derive computed data or trigger side effects when something changes. Statements prefixed with a $: label are reactive. They'll be recomputed when data used in the reactive statement is updated.

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

When todos or showCompleted change, visibleTodos will be updated.

TodoList.svelte

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

  let todos = [];
  let showCompleted = false;

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

  function addTodo(task) {
    todos = todos.concat([{
      task,
      completed: false,
    }]);
  }
</script>

{#each visibleTodos as todo}
  <Todo {...todo} />
{/each}

{#if showCompletedTodos}
  <button on:click={() => showCompleted = false}>
    Hide completed
  </button>
{:else}
  <button on:click={() => showCompleted = true}>
    Show completed
  </button>
{/if}

Reactive statements can also be used to trigger side effects.

Multiple statements can be grouped in a reactive block.

let todos = [];

$: console.log(todos);
let todos = [];
let showCompleted = false;

$: if (showCompleted) {
  console.log(todos);
}
let todos = window.localStorage
  ? JSON.parse(window.localStorage.getItem('todos') || '[]')
  : [];

$: {
  console.log(todos);

  if (window.localStorage) {
    window.localStorage.setItem(
      'todos',
      JSON.stringify(todos),
    );
  }
}