Bird
Raised Fist0
Svelteframework~20 mins

setContext in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Svelte Context Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Svelte code using setContext and getContext?

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?

Svelte
/* 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>
AThe child component throws a runtime error
BThe child component displays: undefined
CThe child component displays: blue
DThe child component displays: null
Attempts:
2 left
💡 Hint

Remember that setContext shares data with descendants, and getContext retrieves it.

❓ state_output
intermediate
2:00remaining
What is the value of the variable after using setContext and getContext with reactive stores?

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?

Svelte
/* 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>
AInitially 0, then updates to 5 after 100ms
BInitially 5, then updates to 0 after 100ms
CAlways 0, does not update
DThrows an error because stores cannot be passed via context
Attempts:
2 left
💡 Hint

Writable stores are reactive and can be shared via context.

📝 Syntax
advanced
2:00remaining
Which option correctly uses setContext in a Svelte component?

Choose the code snippet that correctly sets a context value in a Svelte component.

A<script>import { setContext } from 'svelte'; setContext('key' 123);</script>
B<script>import { setContext } from 'svelte'; setContext('key', 123);</script>
C<script>import { setContext } from 'svelte'; setContext('key');</script>
D<script>import { setContext } from 'svelte'; setContext(123, 'key');</script>
Attempts:
2 left
💡 Hint

Check the function signature: setContext(key, value).

🔧 Debug
advanced
2:00remaining
Why does this Svelte child component get undefined from getContext?

A parent sets context with setContext('user', {name: 'Anna'}). The child calls getContext('user') but gets undefined. What is the most likely reason?

Svelte
/* 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>
AThe child is not a descendant of the parent component that called setContext
BsetContext must be called inside onMount lifecycle
CThe key 'user' is misspelled in the child component
DgetContext only works with primitive values, not objects
Attempts:
2 left
💡 Hint

Context only works down the component tree.

🧠 Conceptual
expert
3:00remaining
How does Svelte's setContext differ from React's Context API in component communication?

Choose the statement that best describes a key difference between Svelte's setContext and React's Context API.

ASvelte's setContext automatically updates all components on data change, React's Context requires manual subscription
BSvelte's setContext shares data only with direct descendants, React's Context can be accessed by any nested component regardless of depth
CSvelte's setContext requires a store to share data, React's Context only shares static values
DSvelte's setContext is synchronous and scoped to a component subtree, React's Context uses a Provider component and can trigger re-renders on consumers
Attempts:
2 left
💡 Hint

Think about how data flows and updates happen in both frameworks.

Practice

(1/5)
1. What is the main purpose of setContext in Svelte?
easy
A. To style components using CSS variables
B. To fetch data from an API inside a component
C. To create a reactive variable inside a component
D. To share data or functions from a parent component to its children without using props

Solution

  1. Step 1: Understand the role of setContext

    setContext is used to share data or functions from a parent component to its children without passing props explicitly.
  2. Step 2: Compare with other options

    Options A, B, and C describe unrelated tasks like styling, fetching data, or creating reactive variables, which are not the purpose of setContext.
  3. Final Answer:

    To share data or functions from a parent component to its children without using props -> Option D
  4. Quick Check:

    Sharing data without props = D [OK]
Hint: Remember: setContext shares data down without props [OK]
Common Mistakes:
  • Confusing setContext with fetching data
  • Thinking setContext creates reactive variables
  • Mixing setContext with styling methods
2. Which of the following is the correct syntax to use setContext in a Svelte component?
easy
A. setContext('key');
B. setContext('key', value);
C. setContext(key, value);
D. setContext(value, 'key');

Solution

  1. Step 1: Recall the setContext function signature

    The function takes two arguments: a unique key (usually a variable or symbol) and a value to share.
  2. Step 2: Analyze the options

    setContext(key, value); correctly uses setContext(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.
  3. Final Answer:

    setContext(key, value); -> Option C
  4. Quick Check:

    Correct syntax is setContext(key, value) [OK]
Hint: Use a variable or symbol as key, then value: setContext(key, value) [OK]
Common Mistakes:
  • Using string literals as keys instead of variables or symbols
  • Forgetting the value argument
  • Swapping key and value arguments
3. Given this parent component code:
import { setContext } from 'svelte';
const key = {};
setContext(key, 'hello');

And a child component that uses:
import { getContext } from 'svelte';
const value = getContext(key);
console.log(value);

What will be logged in the console?
medium
A. An error because key is not defined in child
B. 'hello'
C. undefined
D. null

Solution

  1. Step 1: Check how key is used in parent and child

    In the parent, key is a local constant object. In the child, key is used but not imported or defined, so it is undefined in that scope.
  2. Step 2: Understand the effect on getContext(key)

    Since key is not defined in the child, this causes a ReferenceError at runtime.
  3. Final Answer:

    An error because key is not defined in child -> Option A
  4. Quick Check:

    Undefined key in child causes error = B [OK]
Hint: Always import or define the same key in child to avoid errors [OK]
Common Mistakes:
  • Assuming string keys work without importing key
  • Expecting undefined instead of error
  • Not realizing key must be shared or imported
4. Identify the error in this Svelte parent component code using setContext:
import { setContext } from 'svelte';
const key = Symbol();
setContext(key);
medium
A. Missing value argument in setContext call
B. Using Symbol() as key is invalid
C. setContext must be imported from 'svelte/store'
D. Key must be a string, not a Symbol

Solution

  1. Step 1: Review setContext usage

    The setContext function requires two arguments: a key and a value to share.
  2. Step 2: Check the code for missing arguments

    The code calls setContext(key); with only one argument, missing the value argument.
  3. Final Answer:

    Missing value argument in setContext call -> Option A
  4. Quick Check:

    setContext needs key and value [OK]
Hint: Always provide both key and value to setContext [OK]
Common Mistakes:
  • Forgetting the value argument
  • Thinking Symbol keys are invalid
  • Importing setContext from wrong module
5. You want to share a function from a parent to multiple nested child components using setContext. Which approach correctly ensures all children can access the function safely?
hard
A. Use a string key like 'sharedFunc' directly in setContext and getContext calls without importing
B. Define a unique Symbol key in a separate module, import it in parent and children, then use setContext(key, func) in parent and getContext(key) in children
C. Pass the function as a prop to each child instead of using setContext
D. Define the function inside each child component separately

Solution

  1. Step 1: Understand key uniqueness and sharing

    Using a unique Symbol key defined in a separate module and imported ensures the same key is used in parent and children, avoiding collisions.
  2. Step 2: Compare with other options

    Use a string key like 'sharedFunc' directly in setContext and getContext calls without importing risks key collisions and is less safe. Pass the function as a prop to each child instead of using setContext works but is not using setContext. Define the function inside each child component separately duplicates code and is not sharing.
  3. Final Answer:

    Define a unique Symbol key in a separate module, import it in parent and children, then use setContext(key, func) in parent and getContext(key) in children -> Option B
  4. Quick Check:

    Unique shared key via module = A [OK]
Hint: Use a shared Symbol key imported by all components [OK]
Common Mistakes:
  • Using string keys without sharing the key variable
  • Passing functions only via props when setContext fits better
  • Duplicating function code in children
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard