Basic Context Usage
The parent component sets context withsetContext(key, value):
getContext(key):
<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 />
<script>
import { getContext } from 'svelte';
const config = getContext('app-config');
</script>
<div class="{config.theme}">
API: {config.apiUrl}
</div>
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
UsecreateContext 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
- Use unique keys - Avoid key collisions by using symbols or unique strings
- Set during initialization - Context must be set during component setup
- Document context contracts - Make it clear what context keys are available
- Prefer type-safe context - Use
createContextfor better type safety - Don’t overuse - Context is not a replacement for props
- Consider scope - Context is available to all descendants, not just direct children