Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 35 ยท State Beyond One Component

The Context API

Share data with a component subtree using setContext and getContext in Svelte 5, combine it with reactive state, and avoid global state issues.

Module state is global: everyone who imports it shares the same thing. Sometimes you want something in between props and globals: data available to a component and all its descendants, without passing it through every layer, but private to that part of the tree. That is what context is for.

Typical uses: a theme for one section of the page, form state shared by the fields of one form, a tabs component sharing the active tab with its tab panels, the current user in a SvelteKit app.

setContext and getContext

A component provides a value under a key with setContext. Any descendant reads it with getContext:

SVELTE
<!-- ThemeProvider.svelte -->
<script>
  import { setContext } from 'svelte';
  let { theme = 'light', children } = $props();

  setContext('theme', { name: theme });
</script>

<div class="theme-{theme}">
  {@render children?.()}
</div>
SVELTE
<!-- ThemedButton.svelte (deep inside the tree) -->
<script>
  import { getContext } from 'svelte';
  const theme = getContext('theme');
</script>

<button class="btn-{theme.name}">Press</button>

Rules:

  • Call setContext and getContext during component initialization (at the top of the script), not later inside an event handler or after an await.
  • The key can be any value; strings work, but a Symbol or a unique object avoids accidental collisions.
  • Context is available to descendants only. Siblings and parents cannot read it.
  • Each subtree can provide its own value, and a nearer provider wins over a farther one.

Context flow

Provider setContext(key, value)
Any depth No prop drilling
Consumer getContext(key)

Only descendants of the provider can read it.

1 / 2

Making context reactive

Context itself is not reactive: it just hands over the value. If you store a plain string, it never changes for the consumer. Put reactive state inside the context value, as an object or class:

SVELTE
<!-- Tabs.svelte -->
<script>
  import { setContext } from 'svelte';
  let { children } = $props();

  const tabs = $state({ active: 'one' });
  setContext('tabs', tabs);
</script>

<div class="tabs">{@render children?.()}</div>
SVELTE
<!-- Tab.svelte -->
<script>
  import { getContext } from 'svelte';
  let { id, label } = $props();
  const tabs = getContext('tabs');
</script>

<button class:active={tabs.active === id} onclick={() => (tabs.active = id)}>
  {label}
</button>

tabs.active is read in the template, so changing it from any Tab updates all of them. Do not pass tabs.active alone (a string): you would hand over a copy.

A tidy pair of helpers

Wrap the key and types in a pair of functions so consumers never touch the key:

JavaScript
// theme-context.js
import { getContext, setContext } from 'svelte';

const KEY = Symbol('theme');

export function provideTheme(theme) {
  return setContext(KEY, theme);
}

export function useTheme() {
  const theme = getContext(KEY);
  if (!theme) throw new Error('useTheme() must be used inside <ThemeProvider>');
  return theme;
}

Newer Svelte 5 releases include createContext (from svelte), which returns a typed [get, set] pair and throws a clear error when the context is missing. If your version has it, it replaces the hand-written helpers above. Check the version you installed.

Context and the server

In SvelteKit, module-level state lives for the whole server process, so it is shared across requests (see the previous lesson). Context is created per render, so it is the safe place for per-request or per-user data: create the store in your root layout, call setContext, and let children getContext. This is the recommended way to share a user's data on server-rendered pages.

Context versus props versus modules

Tool Scope Good for
Props parent to child most data, explicit and easy to follow
Context one subtree compound components, themes, per-request data
Module state whole app global singletons that are the same for everyone

Do not reach for context when one level of props would do. Invisible data flow is harder to understand than explicit props.

Stand-in: context as a scope chain

Context behaves like variable scope across a tree. This stand-in builds a tiny tree where each node can provide values and children look them up by walking to the nearest provider.

JS Nearest provider wins (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Tabs sharing an active id (stand-in page)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who can read a context value set by a component?

    Context is scoped to the subtree below the provider.
  2. 2. When must setContext and getContext be called?

    They rely on the component currently being created, so call them at the top level of the script.
  3. 3. How do you make context values reactive?

    Context only transports the value. A $state object keeps its reactivity when shared.
  4. 4. Why is context safer than module state for per-user data in SvelteKit?

    Module state lives for the whole server process; context belongs to one render.

Summary

  • setContext(key, value) provides a value to all descendants; getContext(key) reads the nearest one.
  • Call both at component initialization; use Symbols or helper functions for keys.
  • Context is not reactive by itself: share a $state object or class instance.
  • Prefer context over module state for per-request data on the server.

Next: Svelte Stores