Consider a parent component that uses setContext to share a value, and a child component that uses getContext to access it. What will the child display?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; setContext('color', 'blue'); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const color = getContext('color'); </script> <p>{color}</p>
Remember that setContext shares data with descendants, and getContext retrieves it.
The setContext function sets a value with a key that descendants can access using getContext. Here, the child gets the string 'blue' and displays it.
In Svelte, if a parent sets a writable store in context and the child subscribes to it, what will the child display after the store updates?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; import { writable } from 'svelte/store'; import Child from './Child.svelte'; const count = writable(0); setContext('count', count); setTimeout(() => count.set(5), 100); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const count = getContext('count'); let value = 0; const unsubscribe = count.subscribe(v => value = v); // Optional: unsubscribe on destroy </script> <p>{value}</p>
Writable stores are reactive and can be shared via context.
The parent sets a writable store in context. The child subscribes to it and updates its local variable when the store changes. After 100ms, the store updates to 5, so the child shows 5.
Choose the code snippet that correctly sets a context value in a Svelte component.
Check the function signature: setContext(key, value).
The setContext function requires two arguments: a key and a value. Option B correctly passes both.
A parent sets context with setContext('user', {name: 'Anna'}). The child calls getContext('user') but gets undefined. What is the most likely reason?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; import Child from './Child.svelte'; setContext('user', {name: 'Anna'}); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const user = getContext('user'); </script> <p>{user?.name}</p>
Context only works down the component tree.
If the child is not a descendant of the component that called setContext, it will get undefined. The key and value types are correct, and setContext can be called anywhere in the component script.
Choose the statement that best describes a key difference between Svelte's setContext and React's Context API.
Think about how data flows and updates happen in both frameworks.
Svelte's setContext shares data synchronously within a component subtree and does not itself trigger reactive updates; reactivity depends on the data passed (like stores). React's Context uses a Provider component and triggers re-renders in consumers when the context value changes.