0
0
SvelteHow-ToBeginner · 3 min read

How to Use getContext in Svelte: Simple Guide with Examples

In Svelte, use getContext inside a child component to access data or functions provided by an ancestor component via setContext. This allows components to share information without passing props through every level.
📐

Syntax

The getContext function takes a single argument, a key, which is used to retrieve the value set by setContext in an ancestor component.

Example parts:

  • const value = getContext(key); - retrieves the value associated with key.
  • key - usually a string or symbol used to identify the context.
svelte
import { getContext } from 'svelte';

const value = getContext('myKey');
💻

Example

This example shows a parent component setting a context value with setContext and a child component accessing it with getContext. The child displays the shared message.

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

  const message = 'Hello from context!';
  setContext('greeting', message);
</script>

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


<!-- Child.svelte -->
<script>
  import { getContext } from 'svelte';

  const greeting = getContext('greeting');
</script>

<p>Child says: {greeting}</p>
Output
<h1>Parent Component</h1> <p>Child says: Hello from context!</p>
⚠️

Common Pitfalls

  • Missing setContext: Calling getContext without a matching setContext in an ancestor returns undefined.
  • Wrong key: The key used in getContext must exactly match the one used in setContext.
  • Not reactive: Values from context are not reactive by default; use stores if you want reactivity.
svelte
<!-- Wrong usage example -->
<script>
  import { getContext } from 'svelte';

  // No setContext in parent, so this returns undefined
  const data = getContext('missingKey');
</script>

<p>{data}</p>

<!-- Correct usage example -->
<script>
  import { setContext, getContext } from 'svelte';

  setContext('key', 'value');
  const data = getContext('key');
</script>

<p>{data}</p>
Output
<p>undefined</p> <p>value</p>
📊

Quick Reference

  • setContext(key, value): Used in a parent component to provide data.
  • getContext(key): Used in a child component to access provided data.
  • Key: Can be a string or symbol; must match exactly.
  • Use case: Share data deeply without prop drilling.

Key Takeaways

Use getContext with the exact key used in setContext to access shared data.
setContext must be called in an ancestor component before getContext can retrieve the value.
Context values are not reactive by default; use Svelte stores for reactive shared state.
getContext helps avoid passing props through many component layers.
Keys can be strings or symbols but must match exactly between setContext and getContext.