Lesson 14 / 25

The Context API

Share values down a component tree.

setContext and getContext

setContext(key, value) makes a value available to a component and all its descendants; getContext(key) reads it; hasContext(key) checks for it. Both must be called during component initialisation (top level of the script), not in event handlers or effects. Context is not reactive by itself, so pass a $state object or class instance and mutate its properties. Because each component tree gets its own context, context is the safe way to share per-request state during SSR. Wrapping the calls in typed helper functions avoids string keys spread across the codebase. Newer Svelte 5 versions add a createContext helper; check the docs for your version.

Typed context helpers

Provide a cart in a layout, read it deeper down.

// src/lib/cart-context.ts
import { getContext, setContext } from 'svelte';
import { Cart } from './cart.svelte';

const KEY = Symbol('cart');

export function provideCart(): Cart {
  return setContext(KEY, new Cart());
}

export function useCart(): Cart {
  const cart = getContext<Cart | undefined>(KEY);
  if (!cart) throw new Error('useCart() called outside provideCart()');
  return cart;
}

// +layout.svelte:   <script lang="ts"> import { provideCart } from '$lib/cart-context'; provideCart(); ... </script>
// CartBadge.svelte: <script lang="ts"> const cart = useCart(); </script> <span>{cart.lines.length}</span>

A family recipe book

Context is a book handed down through one family: every descendant can read it, but neighbouring families have their own copy.

Quick check: Where must getContext be called?

  • Only inside +server.ts files
  • Inside an onclick handler
  • Inside a setTimeout callback
  • At the top level of a component script during initialisation
Answer

At the top level of a component script during initialisation — Context is tied to component creation.