Consider a parent component that sets a context key and a child component that reads it. What will the child display?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; setContext('user', { name: 'Alice' }); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const user = getContext('user'); </script> <p>{user.name}</p>
Remember that setContext shares data with descendants using the same key.
The parent sets the context key 'user' with an object containing name: 'Alice'. The child retrieves this context and displays user.name, so it outputs 'Alice'.
Identify the option that uses valid Svelte syntax to set and get a context key named 'theme'.
Check that the key is a string and the value is provided when setting context.
Option D correctly uses a string key 'theme' and provides a value 'dark' to setContext. The getContext call uses the same string key. Other options either omit the value or use an undefined variable as key.
Given the parent sets context with setContext('data', 123), why does the child get undefined when calling getContext('data')?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; setContext('data', 123); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const data = getContext('data'); console.log(data); </script>
Think about how Svelte context works with component hierarchy.
Context in Svelte only works between components in a parent-child relationship. If the child is not actually nested inside the parent in the component tree, it won't receive the context and getContext returns undefined.
In this example, the parent updates the context value after 1 second. What does the child display before and after the update?
/* Parent.svelte */ <script> import { setContext } from 'svelte'; import { writable } from 'svelte/store'; const count = writable(0); setContext('count', count); setTimeout(() => count.set(5), 1000); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const count = getContext('count'); </script> <p>{$count}</p>
Remember that Svelte stores are reactive and can be shared via context.
The parent sets a writable store as context. The child subscribes to it with {$count}. When the store updates after 1 second, the child automatically updates the displayed value.
When multiple libraries or components use context keys, how can you ensure keys do not collide?
Think about JavaScript features that guarantee uniqueness.
Symbols are unique and immutable, so using them as context keys prevents accidental collisions between different parts of an app or libraries. Prefixing strings helps but does not guarantee uniqueness.