CHAPTER 19
Beginner
Context API and Advanced State Management
Updated: May 18, 2026
5 min read
# CHAPTER 19
Context API and Advanced State Management
1. Chapter Introduction
When a deeply nested component needs data from a distant ancestor, prop drilling through every intermediate component is painful. Svelte's Context API (setContext/getContext) provides a clean solution. Combined with advanced store patterns, you can build sophisticated, scalable state management for large applications.
2. Learning Objectives
-
Use
setContextandgetContextto share data in component trees.
- Understand the difference between Context and Stores.
- Build custom store factories.
- Implement the store pattern for complex features.
3. Context API: setContext / getContext
svelte
svelte
svelte
4. Context vs Stores
| Feature | Context | Stores |
|---|---|---|
| Scope | Subtree of descendants | Entire application |
| Reactive | Yes (with stores inside) | Yes |
| SSR safe | Yes (per-request) | Careful (shared across requests) |
| Use case | UI themes, shared config for a feature | Global auth, cart, preferences |
5. Custom Store Factory
A store factory creates configurable store instances — perfect for features that need multiple independent instances:
javascript
svelte
6. Auth Store Pattern
javascript
svelte
7. Common Mistakes
- Using context for global state: Context is scoped to a component subtree. For truly global state (available everywhere), use a module-level store instead.
-
Setting context in
onMount:setContextmust be called during component initialization (synchronously in<script>), not insideonMount.
8. MCQs
Question 1
What function provides data to all descendant components?
Question 2
What function retrieves context in a descendant component?
Question 3
When must setContext be called?
Question 4
What is the primary use case for Context vs Stores?
Question 5
What does a custom store factory return?
Question 7
How do you make context reactive in Svelte?
Question 8
Can you have multiple independent instances of a store?
Question 9
What is prop drilling and why is it a problem?
Question 10
How does derived work with a custom store?
9. Interview Questions
setContext/getContext over a Svelte store for shared state?