0
0
SvelteHow-ToBeginner · 3 min read

How to Use Context in Svelte: Simple Guide with Examples

In Svelte, you use setContext to provide data in a parent component and getContext to access that data in child components. This allows components to share information without passing props through every level.
📐

Syntax

Use setContext(key, value) in a parent component to store data. Use getContext(key) in a child component to retrieve that data. The key is usually a string or a Symbol to identify the context.

svelte
<script>
  import { setContext, getContext } from 'svelte';

  // Parent.svelte
  setContext('myKey', 'some value');

  // Child.svelte
  const value = getContext('myKey');
</script>
💻

Example

This example shows a parent component setting a context value and a child component reading and displaying it.

svelte
<!-- Parent.svelte -->
<script>
  import { setContext } from 'svelte';
  import Child from './Child.svelte';

  setContext('user', { name: 'Alice', age: 30 });
</script>

<main>
  <h1>Parent Component</h1>
  <Child />
</main>


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

<p>User name: {user.name}</p>
<p>User age: {user.age}</p>
Output
Parent Component User name: Alice User age: 30
⚠️

Common Pitfalls

  • Trying to use getContext in a component that is not a descendant of the component that called setContext will return undefined.
  • Using the same key in multiple places can cause conflicts; use unique keys like Symbols.
  • Context is not reactive by default; if the context value changes, children won’t update unless you use stores.
svelte
<!-- Wrong: getContext used outside parent hierarchy -->
<script>
  import { getContext } from 'svelte';
  const value = getContext('missingKey'); // returns undefined
</script>

<!-- Right: Use unique Symbol keys -->
<script>
  import { setContext, getContext } from 'svelte';
  const key = Symbol('uniqueKey');
  setContext(key, 'value');
  const value = getContext(key);
</script>
📊

Quick Reference

FunctionPurposeUsage
setContextStores data in a parent componentsetContext(key, value)
getContextRetrieves data in a child componentconst value = getContext(key)
keyIdentifier for context dataUsually a string or Symbol

Key Takeaways

Use setContext in a parent to share data with descendants.
Use getContext in child components to access shared data.
Keys should be unique, preferably Symbols, to avoid conflicts.
Context is not reactive by default; use stores for reactive data.
getContext returns undefined if used outside the provider hierarchy.