0
0
Svelteframework~5 mins

Why context shares data without prop drilling in Svelte

Choose your learning style9 modes available
Introduction

Context lets components share data easily without passing it through many layers. This avoids the hassle of sending props step-by-step.

You want to share a theme or style setting across many components.
You need to share user login info with deep nested components.
You want to avoid passing the same data through many intermediate components.
You have global settings that many parts of your app need to read.
You want cleaner code without extra props everywhere.
Syntax
Svelte
import { setContext, getContext } from 'svelte';

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

// In a child or nested component
const value = getContext('key');

setContext shares data from a parent component.

getContext retrieves that data in any nested child component.

Examples
This sets a color value 'blue' in the context with the key 'color'.
Svelte
import { setContext } from 'svelte';

setContext('color', 'blue');
This gets the 'color' value from context in a nested component.
Svelte
import { getContext } from 'svelte';

const color = getContext('color');
Sample Program

The parent sets a user object in context. The child gets it directly without props. It shows "Hello, Anna!".

Svelte
<script>
  import { setContext } from 'svelte';
  import Child from './Child.svelte';

  // Parent component
  setContext('user', { name: 'Anna' });
</script>

<Child />
OutputSuccess
Important Notes

Context only works between parent and nested children, not unrelated components.

Use unique keys to avoid conflicts in context data.

Context helps keep your code clean and easier to maintain.

Summary

Context shares data without passing props through every component.

Use setContext in a parent and getContext in children.

This makes your app simpler and cleaner.