Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Reactive Context in Svelte

| Comments

The context API in svelte provides a way for components to communicate to each other without passing around data, functions props, or dispatching events!

Let us see a quick example:

1
2
3
4
5
6
7
8
// Parent has something like:
<script>
import { setContext } from 'svelte'

const state = {}

setContext('state', state)
</script>
1
2
3
4
5
6
// In the descendants/child components
<script>
import { getContext } from 'svelte'

const state = getContext('state')
</script>

That was easy, but say you have sistuation where the context need to be update later in time, to emulate we could setTimeout(() => {setContext('state', {})},1000) this would not reflect either in the parent or the child component.

store comes to our resuse in these cases:

1
2
3
4
5
6
7
8
9
// 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 assigment operation.
1
2
3
4
5
// In the child component:
import {getContext} from 'svelte';
const state = getContext('state')

// Access it like any other state variable, in this case `$state`

Here is a quick example:


This is explictily mentoined in the API docs too:

Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.

Comments