Svelte Context API

Context leaves a value from a parent for all its descendants without prop drilling: setContext("formatPrice", formatPrice) in App, const formatPrice =…

The kitchen at Mrs. Sri's stall has a notice board. Early in the morning Mrs. Sri writes "prices are written $15.00, not 15" and pins it up once. Everyone in that kitchen just reads the board, with no message passed from person to person. Another branch's kitchen has its own board. But the board is paper: if Mrs. Sri changes her mind at noon and doesn't rewrite the board, whoever reads it still sees the morning's note.

In Svelte, that board is called context: how a component leaves a value for all of its descendants, children, grandchildren and further down, without passing it through props at every level. The parent calls setContext(key, value), and any descendant picks it up with getContext(key). If you come from React, this is a cousin of useContext. From Vue, it's provide and inject.

The problem: prop drilling

Mrs. Sri's stall has three levels of components: App.svelte mounts MenuList.svelte, and MenuList mounts one MenuItem.svelte per dish. MenuItem needs a formatPrice function to write prices, but that function lives in App. With props, MenuList has to take formatPrice and pass it on to each MenuItem, even though MenuList never uses it. Passing props through components that are only go-betweens like this is called prop drilling. The deeper the component tree, the more go-betweens have to change along with it.

setContext and getContext

<!-- App.svelte -->
<script>
  import { setContext } from "svelte"
  import MenuList from "./MenuList.svelte"

  function formatPrice(amount) {
    return "$" + amount.toFixed(2)
  }

  setContext("formatPrice", formatPrice)
</script>

<h1>Mrs. Sri's Stall</h1>
<MenuList />
<!-- MenuItem.svelte -->
<script>
  import { getContext } from "svelte"

  let { name, price } = $props()

  const formatPrice = getContext("formatPrice")
</script>

<li>{name}: {formatPrice(price)}</li>

MenuList only writes <MenuItem name={m.name} price={m.price} /> inside {#each}, without mentioning formatPrice at all. The result is Fried Rice: $15.00, Chicken Noodles: $12.00, Iced Tea: $5.00.

Other options: createContext, since Svelte 5.40. This function makes a getter and a setter as a pair, with no string key. Write it once in its own file, then import it in the parent and in the descendants:

// price-context.js
import { createContext } from "svelte"

export const [getPriceFormat, setPriceFormat] = createContext()

App calls setPriceFormat(formatPrice), and MenuItem calls const formatPrice = getPriceFormat(). With no string key, a mismatch in upper and lower case such as "Theme" and "theme" can't happen. If no parent has set the value yet, getPriceFormat() doesn't quietly give undefined. Svelte stops with the error missing_context. For new code on Svelte 5.40 or newer, this is the safer choice. The exercise editor (Svelte 5.16) doesn't have createContext yet, so the exercises still use setContext and getContext.

Only while the component is created

setContext and getContext have to be called directly in <script>, while the component is being created. Inside a click handler, a setTimeout, or after an await, Svelte 5 refuses with an error:

`getContext(...)` can only be used during component initialisation

So read the context once at the start into a const, then use that const in handlers: const formatPrice = getContext("formatPrice"), then onclick={() => alert(formatPrice(price))}.

Context isn't reactive: leave a $state object

Say App writes let theme = $state("light") and then setContext("theme", theme). What's left is the value theme has at that moment, the string "light". The assignment theme = "dark" in App afterwards only changes App's variable. What was left is still "light", so MenuItem stays light. The Svelte 5 compiler even warns on that setContext line: State referenced in its own scope will never update. That is the text from the exercise editor (Svelte 5.16). Svelte 5.57 gives the same warning, state_referenced_locally, with new text: This reference only captures the initial value of `theme`. Did you mean to reference it inside a closure instead?

For the descendants to follow along, leave a $state object, then change what's inside it, not the object. The object itself is never replaced, only theme.color changes, and $state tracks changes all the way inside the object (the Reactivity lesson):

<!-- App.svelte -->
<script>
  import { setContext } from "svelte"

  const theme = $state({ color: "light" })
  setContext("theme", theme)

  function toggleTheme() {
    theme.color = theme.color === "light" ? "dark" : "light"
  }
</script>

<button onclick={toggleTheme}>Switch theme</button>
<!-- MenuItem.svelte -->
<script>
  import { getContext } from "svelte"

  let { name } = $props()
  const theme = getContext("theme")
</script>

<li class={theme.color}>{name}</li>

The result:

Switch theme clicks Theme in App MenuItem, plain value MenuItem, $state object
none light light light
1 dark light dark
2 light light light

Replacing the object, theme = { color: "dark" }, brings back the first problem: MenuItem still holds the old object. That's why theme is written as a const.

Context or a plain store?

In the Stores lesson, cart is a store exported from cart.js. Every component that imports it uses the same store: one value for the whole app. A $state object exported from a .svelte.js file works the same way. Context is different: its value only holds for the component that left it and its descendants, and it can differ per branch of the component tree.

Say App mounts two <Branch>: <Branch name="Market" initial="light" /> and <Branch name="Campus" initial="dark" />. Each Branch makes const theme = $state({ color: initial }) and then runs setContext("theme", theme). MenuItems in the Market branch read light, MenuItems in the Campus branch read dark, and changing Market's theme doesn't change Campus. If both used state from one shared file, changing one would change them all.

A store from a .js file Context
Reach the whole app that component and its descendants
Its value one for everyone can differ per branch
Reactive yes only if it holds a $state object or a store
Read from any file, any time descendants, while being created

SvelteKit adds one more reason: on the server, a store from a .js file (and a $state object from a .svelte.js file) is shared by every visitor, while context is created afresh for each page that's rendered. Data that belongs to one user is safer in context.

Exercise: parent and child in one file

The exercise editor only runs one component, so the same component plays parent and child. That still works, because getContext also reads what that component itself left:

<script>
  import { setContext, getContext } from "svelte"

  setContext("theme", "dark")
  const theme = getContext("theme")
</script>

<p>Theme: {theme}</p>

The paragraph reads Theme: dark. The second exercise has the same shape: setContext("user", { name: "Andi", role: "admin" }), const user = getContext("user"), then <p>{user.name} ({user.role})</p> becomes Andi (admin). The values never change, so no $state is needed.

Older code: a store in context

In Svelte 4 code, context that can change almost always holds a store, because Svelte 4 had no $state:

<!-- App.svelte, Svelte 4 style -->
<script>
  import { setContext } from "svelte"
  import { writable } from "svelte/store"

  const theme = writable("light")
  setContext("theme", theme)
</script>

<button on:click={() => theme.update((t) => (t === "light" ? "dark" : "light"))}>Switch theme</button>

Descendants read $theme, for example <li class={$theme}>. A store in context still works in Svelte 5, so you'll meet this form often. The error outside initialisation also reads differently in Svelte 4: Function called outside component initialization.

⚠️ Context that comes back empty or doesn't follow changes

TL;DR: Context leaves a value from a parent for all its descendants without prop drilling: setContext("formatPrice", formatPrice) in App, const formatPrice = getContext("formatPrice") in MenuItem, and MenuList in between needs to know nothing. Both are imported from "svelte" and may only be called while the component is created; in a handler, Svelte 5 throws `getContext(...)` can only be used during component initialisation. getContext searches upwards, the nearest wins, the key has to match exactly, and it only goes down. Context isn't reactive: what's left is the value at that moment, so for a theme that can change, leave $state({ color: "light" }) and change theme.color, not the object. A store or $state from a shared file holds for the whole app; context holds per component tree and can differ per branch. In Svelte 4 code, context that changes holds a store and is read with $theme. The exercises: setContext("theme", "dark") and getContext("theme") for Theme: dark, then the user object for Andi (admin).

⚡ setContext leaves it, getContext picks it up

Write:

<!-- App.svelte -->
<script>
  import { setContext } from "svelte"

  function formatPrice(amount) {
    return "$" + amount.toFixed(2)
  }

  setContext("formatPrice", formatPrice)
</script>
<!-- MenuItem.svelte -->
<script>
  import { getContext } from "svelte"

  let { name, price } = $props()

  const formatPrice = getContext("formatPrice")
</script>

<li>{name}: {formatPrice(price)}</li>

Meaning: The parent leaves a value with setContext(key, value), and any descendant picks it up with getContext(key). MenuList in between needs to know nothing about formatPrice, so there's no prop drilling.

⚡ Context isn't reactive

Guess first: App writes let theme = $state("light"), then setContext("theme", theme). Later App runs theme = "dark". Does MenuItem turn dark?

No. What was left is the value theme had at that moment, the string "light". The change afterwards only changes App's own variable.

Meaning: For a theme that can change, leave a $state({ color: "light" }) object as a const, then change what's inside it, theme.color, not the object.

⚡ Context per tree, a store for everyone

Meaning: A store from a .js file holds for the whole app, one value for everyone. Context only holds for the component that left it and its descendants, so its value can differ per branch: the Market branch light, the Campus branch dark.

What you will learn