0
0
Svelteframework~5 mins

Context key patterns in Svelte

Choose your learning style9 modes available
Introduction

Context key patterns help you share data between components without passing props all the time. It makes your code cleaner and easier to manage.

You want to share a theme or style settings across many components.
You need to pass user information from a top component to deep nested components.
You want to avoid passing the same data through many layers of components.
You want to share a function or state globally within a part of your app.
Syntax
Svelte
import { setContext, getContext } from 'svelte';

// In parent component
setContext(key, value);

// In child component
const value = getContext(key);

The key can be any value, but using a Symbol is best to avoid conflicts.

Only components inside the parent can access the context with the same key.

Examples
This example uses a simple string as the key to share a color value.
Svelte
// Using a string key
import { setContext, getContext } from 'svelte';

// Parent.svelte
setContext('color', 'blue');

// Child.svelte
const color = getContext('color');
Using a Symbol as the key helps avoid accidental key conflicts.
Svelte
// Using a Symbol key
import { setContext, getContext } from 'svelte';

const THEME = Symbol('theme');

// Parent.svelte
setContext(THEME, { background: 'white' });

// Child.svelte
const theme = getContext(THEME);
Sample Program

This example shows how to share user data using a Symbol key stored in a separate file. This avoids key mismatches and allows the child component to access the user info correctly.

Svelte
<!-- Parent.svelte -->
<script>
  import { setContext } from 'svelte';
  import Child from './Child.svelte';
  import { USER } from './userKey.js';
  const user = { name: 'Alice', loggedIn: true };
  setContext(USER, user);
</script>

<h1>Welcome to the app</h1>
<Child />

<!-- Child.svelte -->
<script>
  import { getContext } from 'svelte';
  import { USER } from './userKey.js';
  const user = getContext(USER);
</script>

<p>User name: {user.name}</p>
<p>Logged in: {user.loggedIn ? 'Yes' : 'No'}</p>

<!-- userKey.js -->
export const USER = Symbol('user');
OutputSuccess
Important Notes

Always use the same key instance (like a shared Symbol) in both setContext and getContext.

Context only works downward in the component tree, not upward or sideways.

Context is great for global-like data but avoid overusing it for everything.

Summary

Context key patterns let you share data easily between components without props.

Use Symbols as keys to avoid conflicts and keep keys unique.

Keep your keys in shared files to use them consistently across components.