Skip to content

Svelte Context API Explained — Dependency Injection

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Svelte Context API Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Svelte's context API (setContext and getContext) provides Dependency Injection for component trees, allowing ancestors to provide data to descendants without prop drilling.

What You'll Learn

  • setContext and getContext
  • Context keys with Symbol
  • Context vs stores
  • Typed context with TypeScript
  • Default context values

Why It Matters

Context prevents prop drilling through deeply nested components. Unlike stores which are global, context is scoped to the component tree, making it ideal for library and layout-level data.

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

  const theme = writable("dark");
  const user = { name: "Alice", role: "admin" };

  setContext("theme", theme);
  setContext("user", user);
</script>

<ThemeProvider>
  <DeepChild />
</ThemeProvider>
<!-- DeepChild.svelte -->
<script>
  import { getContext } from "svelte";

  const theme = getContext("theme");
  const user = getContext("user");
  const defaultConfig = getContext("config") ?? { debug: false };
</script>

<div class:dark={$theme === "dark"}>
  <h2>Welcome {user.name}</h2>
  <button on:click={() => $theme = $theme === "dark" ? "light" : "dark"}>
    Toggle Theme
  </button>
</div>

Expected output: DeepChild accesses theme and user without props. Toggling theme in DeepChild updates the parent's theme store reactively.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro