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.


  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([{
      completed: false,

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

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

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) {
let todos = window.localStorage
  ? JSON.parse(window.localStorage.getItem('todos') || '[]')
  : [];

$: {

  if (window.localStorage) {