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 expose a todos store to child components with context.

Svelte exposes context functions from the svelte package. To make data available down the component tree, use setContext with a key and a value.

To read context from a parent component, use getContext.

App.svelte
<script>
  import { setContext } from 'svelte';

  setContext('theme', 'light');
</script>

<!-- … -->
Component.svelte
<script>
  import { getContext } from 'svelte';

  const theme = getContext('theme');
</script>

<!-- … -->