Concept Flow - setContext
Parent Component
Call setContext(key, value)
Child Component
Call getContext(key)
Access shared value
Use value in child
The parent sets a value with setContext, children get it with getContext using the same key.
import { setContext, getContext } from 'svelte'; // Parent.svelte setContext('color', 'blue'); // Child.svelte const color = getContext('color');
| Step | Component | Action | Key | Value Set/Get | Result |
|---|---|---|---|---|---|
| 1 | Parent | Call setContext | 'color' | 'blue' | Context 'color' set to 'blue' |
| 2 | Child | Call getContext | 'color' | N/A | Retrieves 'blue' from context |
| 3 | Child | Use value | N/A | 'blue' | Child uses 'blue' for rendering or logic |
| 4 | End | No more context calls | N/A | N/A | Execution stops |
| Variable | Start | After Parent setContext | After Child getContext | Final |
|---|---|---|---|---|
| contextMap | {} | { 'color': 'blue' } | { 'color': 'blue' } | { 'color': 'blue' } |
| color | undefined | undefined | 'blue' | 'blue' |
setContext(key, value) shares data from parent to children. Children use getContext(key) to access it. Keys must match exactly. Useful for passing data without props. If key not set, getContext returns undefined.