In Svelte, context lets components share data without passing props through every level. Why does this work?
Think about how context provides data access without needing to pass props through every component.
Svelte context stores data in a way that any component in the tree can access it directly, skipping the need to pass props through intermediate components. This avoids prop drilling.
Given a parent component sets context with setContext('color', 'blue') and a child uses getContext('color'), what color will the child display?
<script> import { setContext, getContext } from 'svelte'; // Parent component setContext('color', 'blue'); </script> <!-- Child component --> <script> import { getContext } from 'svelte'; const color = getContext('color'); </script> <p>{color}</p>
Remember that getContext retrieves the value set by setContext in an ancestor.
The child component accesses the 'color' value set by the parent using getContext. Since the parent set it to 'blue', the child displays 'blue'.
Which option contains a syntax error when setting or getting context in Svelte?
Check the types of arguments passed to setContext and getContext.
setContext requires the first argument to be a string key. Option B passes a variable user instead of a string, causing a syntax or runtime error.
If a parent component sets context with a writable store and updates it, what will a child component using getContext show?
<script> import { writable } from 'svelte/store'; import { setContext, getContext } from 'svelte'; // Parent component const count = writable(0); setContext('count', count); // Later update count.set(5); </script> <!-- Child component --> <script> import { getContext } from 'svelte'; const count = getContext('count'); </script> <p>{$count}</p>
Consider how Svelte stores and reactivity work with context.
The child gets the writable store from context and subscribes to it with $count. Since the parent updated the store to 5, the child shows 5.
Given this code, why does the child component's getContext return undefined?
<!-- Parent.svelte --> <script> import Child from './Child.svelte'; import { setContext, onMount } from 'svelte'; setContext('theme', 'dark'); </script> <Child /> <!-- Child.svelte --> <script> import { getContext } from 'svelte'; const theme = getContext('theme'); </script> <p>{theme}</p>
Think about when and where setContext should be called inside a Svelte component.
setContext must be called inside the component's script block during initialization. Calling it outside the component function means the context is not set in the component tree, so getContext returns undefined.