0
0
Svelteframework~5 mins

getContext in Svelte

Choose your learning style9 modes available
Introduction

getContext lets a Svelte component access data or functions shared by a parent component without passing them through props. It helps components talk to each other easily.

You want a child component to use data or functions from a parent without passing many props.
You have deeply nested components and want to avoid 'prop drilling' through many layers.
You want to share a theme, settings, or state across multiple components.
You want to share a function or store from a parent to children components.
You want to keep components loosely connected but still share important info.
Syntax
Svelte
const value = getContext(key);

key is a unique identifier (usually a string or Symbol) used to find the shared data.

You must use setContext(key, value) in a parent component before children can use getContext(key).

Examples
Get the shared theme object from a parent component.
Svelte
const theme = getContext('theme');
Use a Symbol as a key to avoid naming conflicts when sharing an API object.
Svelte
const api = getContext(Symbol('api'));
Sample Program

The parent sets a theme object in context. The child gets it with getContext and uses it to style text.

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

  // Parent component
  const theme = { color: 'blue', fontSize: '1.2rem' };
  setContext('theme', theme);
</script>

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

<p style="color: {theme.color}; font-size: {theme.fontSize};">
  This text uses the shared theme color and font size.
</p>
OutputSuccess
Important Notes

If getContext is called with a key that was not set, it returns undefined.

Use setContext only in parent components or layout components.

Context is not reactive by itself. If you want reactivity, share a Svelte store in context.

Summary

getContext accesses shared data set by a parent component.

It helps avoid passing many props through nested components.

Use matching keys with setContext and getContext to share info.