---
title: "Reactive Context in Svelte"
description: "Using stores with context API for reactive state in Svelte components. Practical notes and code examples on Reactive Context."
url: "https://h3manth.com/scribe/reactive-context-in-svelte/"
canonical_url: "https://h3manth.com/scribe/reactive-context-in-svelte/"
markdown_url: "https://h3manth.com/scribe/blog/reactive-context-in-svelte.md"
publishDate: "2020-07-04T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["javascript","svelte","frontend"]
word_count: 229
reading_time_minutes: 2
x_markdown_tokens: 486
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Reactive Context in Svelte

> Using stores with context API for reactive state in Svelte components. Practical notes and code examples on Reactive Context.

The [context API](https://github.com/sveltejs/svelte/blob/master/site/content/tutorial/15-context/01-context-api/text.md) in Svelte provides a way for components to communicate to each other without passing around data, functions, props, or dispatching events!

## Basic Example

```javascript
// Parent has something like:
<script>
  import { setContext } from 'svelte'
  const state = {}
  setContext('state', state)
</script>
```

```javascript
// In the descendants/child components
<script>
  import { getContext } from 'svelte'
  const state = getContext('state')
</script>
```

## The Reactivity Problem

That was easy, but say you have a situation where the context needs to be updated later in time. If we try `setTimeout(() => {setContext('state', {})}, 1000)`, this would not reflect either in the parent or the child component.

## Stores to the Rescue

`store` comes to our rescue in these cases:

```javascript
// In the parent component:
import { setContext, getContext } from 'svelte';
import { writable } from 'svelte/store';

let state = writable({color: 'hotpink'});
setContext('state', state);

setTimeout(() => { $state = {color: 'red'} }, 2000);
// ^ Setting the store value after a timeout with assignment operation.
```

```javascript
// In the child component:
import { getContext } from 'svelte';

const state = getContext('state')
// Access it like any other state variable, in this case `$state`
```

> **From the API docs:** Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.
