0
0
Svelteframework~20 mins

setContext in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using setContext in Svelte to Share Data
📖 Scenario: You are building a simple Svelte app where a parent component shares a message with its child component using setContext and getContext.
🎯 Goal: Create a parent component that uses setContext to provide a message string. Then create a child component that uses getContext to receive and display that message.
📋 What You'll Learn
Create a parent Svelte component with a message string
Use setContext in the parent to share the message
Create a child Svelte component
Use getContext in the child to access the message
Display the message inside the child component
💡 Why This Matters
🌍 Real World
Sharing data between components without passing props directly is common in apps with nested components, like theme settings or user info.
💼 Career
Understanding setContext and getContext is important for building scalable Svelte apps where components need to share data cleanly.
Progress0 / 4 steps
1
Create the parent component with a message
In a Svelte component file, create a message variable with the exact string 'Hello from parent!'.
Svelte
Hint

Use let message = 'Hello from parent!' to create the message variable.

2
Use setContext to share the message
Import setContext from 'svelte' and use setContext with the key 'msg' and the message variable to share it.
Svelte
Hint

Use import { setContext } from 'svelte' and then setContext('msg', message).

3
Create a child component that gets the message
In a new Svelte component file, import getContext from 'svelte'. Use getContext('msg') to get the message and store it in a variable called receivedMessage.
Svelte
Hint

Use let receivedMessage = getContext('msg') to get the message from context.

4
Display the received message in the child component
Add markup to the child component to display the receivedMessage variable inside a <p> tag.
Svelte
Hint

Use <p>{receivedMessage}</p> to show the message.