Skip to main content
Context allows components to share data with their descendants without passing props through every level of the component tree, solving the “prop drilling” problem.

Basic Context Usage

The parent component sets context with setContext(key, value):
The child component retrieves it with getContext(key):
1
Setting Context
2
Context must be set during component initialization:
3
<script>
  import { setContext } from 'svelte';
  import Child from './Child.svelte';
  
  const config = {
    apiUrl: 'https://api.example.com',
    theme: 'dark'
  };
  
  setContext('app-config', config);
</script>

<Child />
4
Getting Context
5
Retrieve context in any descendant component:
6
<script>
  import { getContext } from 'svelte';
  
  const config = getContext('app-config');
</script>

<div class="{config.theme}">
  API: {config.apiUrl}
</div>
7
Checking Context
8
Check if context exists before using it:
9
<script>
  import { hasContext, getContext } from 'svelte';
  
  const hasConfig = hasContext('app-config');
  const config = hasConfig ? getContext('app-config') : null;
</script>

{#if config}
  <div>Config available: {config.theme}</div>
{:else}
  <div>No config found</div>
{/if}

Context with Reactive State

Store reactive state in context to share it across components:

Important: Reassignment vs Mutation

Don’t reassign the context object - mutate its properties instead:

Type-Safe Context

Use createContext for type-safe context without explicit keys:

Context API Functions

setContext(key, context)

Associates a context object with the current component:
  • Must be called during component initialization
  • Returns the context value
  • Available to all descendants, including slotted content

getContext(key)

Retrieves context from the closest parent with the specified key:
  • Must be called during component initialization
  • Returns the context value or undefined
  • Looks up the component tree to find the context

hasContext(key)

Checks if a context key exists:

getAllContexts()

Retrieves the entire context map:

Context for Dependency Injection

Context is perfect for dependency injection patterns:

Context vs Global State

Context solves the problem of global state in server-side rendering:

Context with Stores

Combine context with stores for shared reactive state:

Testing with Context

Create wrapper components for testing:

Best Practices

  1. Use unique keys - Avoid key collisions by using symbols or unique strings
  2. Set during initialization - Context must be set during component setup
  3. Document context contracts - Make it clear what context keys are available
  4. Prefer type-safe context - Use createContext for better type safety
  5. Don’t overuse - Context is not a replacement for props
  6. Consider scope - Context is available to all descendants, not just direct children