Svelte Context API

The context API passes data from a parent component down to any of its descendants, no matter how deeply nested those descendants sit. Unlike props, context skips every layer in between without needing each layer to pass the value along manually.

Why Context Matters

A deeply nested component sometimes needs a value that lives several layers above it, such as a theme setting or a logged-in user's details. Passing that value through every layer as a prop clutters components that have no actual use for the value themselves. Context solves this by letting a distant descendant reach up and grab the value directly.

Setting Context In A Parent

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

  setContext("theme", { color: "dark" });
</script>

<Page />

The setContext function stores a value under the label theme, making it available to Page and to every component nested inside Page, regardless of how many layers deep they sit.

Reading Context In A Descendant

<!-- Button.svelte -->
<script>
  import { getContext } from "svelte";

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

<button style="background: {theme.color === 'dark' ? 'black' : 'white'}">
  Click Me
</button>

The getContext function fetches the value stored under the label theme, even though Button never received that value directly from its immediate parent through a prop.

Context Reach Diagram

App.svelte  --- setContext("theme", ...) ---
     |
     v
Page.svelte  (never touches the value directly)
     |
     v
Section.svelte  (never touches the value directly)
     |
     v
Button.svelte  --- getContext("theme") reaches all the way up ---

Section never handles the theme value at all, yet Button still reaches it successfully. Props alone would force Section to accept and pass along a value it has no actual use for.

Context Versus Props

PropsContext
Passes through every layer manuallySkips directly to any descendant
Good for direct parent-to-child dataGood for deeply nested shared data
Every middle layer must forward the valueMiddle layers stay unaware of the value

Context Versus Stores

A store shares data across an entire application, reachable from any file through a simple import. Context ties itself to a specific component tree instead, useful when a value only matters within one particular branch of components, such as a single form or a single page section.

A Layman Analogy

Think of context as a family recipe passed down within one household. A grandchild several generations removed still knows the recipe, without every single relative in between needing to actively teach it forward. The recipe travels down the family line automatically once the grandparent sets it.

Context Sets Only Once Per Component Instance

The setContext function must run during a component's initial setup, not inside a later function like a click handler. Svelte enforces this rule because context ties itself to the moment a component tree gets built, not to an action taken afterward.

Combining Context With A Store

A common pattern places a store inside context, giving each part of a component tree its own independent copy of shared, changeable data.

<script>
  import { setContext } from "svelte";
  import { writable } from "svelte/store";

  setContext("counter", writable(0));
</script>

A descendant reading this context receives a store rather than a fixed value, letting it read and update the shared number using the same dollar sign syntax covered for regular stores.

Key Points

  • setContext stores a value reachable by any nested descendant component
  • getContext retrieves a value set higher up in the same component tree
  • Context avoids passing a value manually through every middle layer
  • Context ties itself to one component tree, unlike a store shared app-wide

Leave a Comment

Your email address will not be published. Required fields are marked *