Svelte logo

Svelte by Example: Context

With context, data can be shared between components without passing it down with props. Context can be useful to share data multiple levels down the component tree.

In this example, we'll share our todos with child components.

Svelte exposes context functions from the svelte package. Call them during component initialization.

Create reactive state inside the component, so each todo list has its own data.

setContext makes a value available to descendants. Keep the same state object, and update its properties to preserve reactivity.

TodoList.svelte
<script>
  import { setContext } from 'svelte';
  import TodoCount from './TodoCount.svelte';




  const list = $state({
    todos: [{ task: 'Walk dog', completed: false }],
  });


  setContext('todos', list);
</script>

<TodoCount />
<button onclick={() => list.todos.push({
  task: 'Read newspaper', completed: false,
})}>Add a todo</button>

getContext reads the value from the nearest parent that provided it. Our count updates when the parent adds a todo.

TodoCount.svelte
<script>
  import { getContext } from 'svelte';

  const list = getContext('todos');
</script>

<p>{list.todos.length} todos</p>