0
0
Svelteframework~5 mins

Context with stores in Svelte

Choose your learning style9 modes available
Introduction

Context with stores lets you share data easily between components without passing props everywhere.

You want to share a theme color across many components.
You need a user login status accessible in different parts of your app.
You want to manage a shopping cart state shared by multiple components.
You want to avoid prop drilling when many nested components need the same data.
Syntax
Svelte
import { writable } from 'svelte/store';
import { setContext, getContext } from 'svelte';

// Create a store
const count = writable(0);

// Provide context in a parent component
setContext('key', count);

// Access context in a child component
const count = getContext('key');

setContext shares data down the component tree.

getContext retrieves that data in child components.

Examples
Set a theme store in context to share the current theme.
Svelte
import { writable } from 'svelte/store';
import { setContext } from 'svelte';

const theme = writable('light');
setContext('theme', theme);
Get the theme store from context and reactively log its value.
Svelte
import { getContext } from 'svelte';

const theme = getContext('theme');

$: console.log($theme);
Share a user store from parent to child using context.
Svelte
import { writable } from 'svelte/store';
import { setContext, getContext } from 'svelte';

// Parent.svelte
const user = writable({ name: 'Anna' });
setContext('user', user);

// Child.svelte
const user = getContext('user');

$: console.log($user.name);
Sample Program

The parent component creates a count store and shares it via context. It also has a button to increase the count. The child component gets the count store from context and shows its current value. When you click the button, the count updates and the child shows the new value.

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

  const count = writable(0);
  setContext('count', count);

  function increment() {
    count.update(n => n + 1);
  }
</script>

<button on:click={increment}>Increment</button>
<slot />


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

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

<p>Count value: {$count}</p>
OutputSuccess
Important Notes

Context only works between parent and child components, not across unrelated components.

Stores in context stay reactive, so changes update all components using them.

Use unique keys for context to avoid conflicts.

Summary

Context with stores shares reactive data easily between components.

Use setContext in a parent and getContext in children.

This avoids passing props through many layers.