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.
setContext in Svelte?setContextsetContext is used to share data or functions from a parent component to its children without passing props explicitly.setContext.setContext in a Svelte component?setContext function signaturesetContext(key, value); where key is a variable or symbol. setContext('key', value); uses a string literal which is discouraged because keys should be unique and not collide. setContext('key'); misses the value argument. setContext(value, 'key'); reverses the arguments.import { setContext } from 'svelte';
const key = {};
setContext(key, 'hello');import { getContext } from 'svelte';
const value = getContext(key);
console.log(value);key is used in parent and childkey is a local constant object. In the child, key is used but not imported or defined, so it is undefined in that scope.getContext(key)key is not defined in the child, this causes a ReferenceError at runtime.setContext:import { setContext } from 'svelte';
const key = Symbol();
setContext(key);setContext usagesetContext function requires two arguments: a key and a value to share.setContext(key); with only one argument, missing the value argument.setContext. Which approach correctly ensures all children can access the function safely?Pass the test and this pattern moves unknown