The context API in Svelte provides a way for components to communicate to each other without passing around data, functions, props, or dispatching events!
Basic Example
// Parent has something like:
<script>
import { setContext } from 'svelte'
const state = {}
setContext('state', state)
</script>
// 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:
// 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.
// 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.
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.