0
0
Svelteframework~10 mins

setContext in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Svelte
import { setContext, getContext } from 'svelte';

// Parent.svelte
setContext('color', 'blue');

// Child.svelte
const color = getContext('color');
Parent shares 'color' value; child retrieves it using the same key.
Execution Table
StepComponentActionKeyValue Set/GetResult
1ParentCall setContext'color''blue'Context 'color' set to 'blue'
2ChildCall getContext'color'N/ARetrieves 'blue' from context
3ChildUse valueN/A'blue'Child uses 'blue' for rendering or logic
4EndNo more context callsN/AN/AExecution stops
💡 No more context calls; child successfully accessed parent's context value
Variable Tracker
VariableStartAfter Parent setContextAfter Child getContextFinal
contextMap{}{ 'color': 'blue' }{ 'color': 'blue' }{ 'color': 'blue' }
colorundefinedundefined'blue''blue'
Key Moments - 2 Insights
Why does the child getContext('color') return 'blue'?
Because the parent called setContext('color', 'blue') before the child tried to get it, as shown in execution_table step 1 and 2.
What happens if the child calls getContext with a key not set by the parent?
getContext returns undefined if no matching key was set, so the child would get no value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value does the child getContext('color') return at step 2?
A'red'
Bundefined
C'blue'
Dnull
💡 Hint
Check the 'Value Set/Get' and 'Result' columns at step 2 in the execution_table.
At which step does the parent set the context value?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table to find when setContext is called.
If the parent did not call setContext, what would the child's getContext('color') return?
Aundefined
B'blue'
Cnull
DError
💡 Hint
Refer to key_moments about what happens if getContext key is not set.
Concept Snapshot
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.
Full Transcript
In Svelte, setContext lets a parent component share data with its children without passing props. The parent calls setContext with a key and value. Children call getContext with the same key to retrieve the value. This works like a hidden shared box. If the child asks for a key not set, it gets undefined. This helps keep components clean and connected. The execution table shows the parent setting 'color' to 'blue' and the child retrieving it successfully.