The context API

However, there are cases where props are not practical. Perhaps 2 components are so distant in the components tree that we’d have to move state up to the top-level component.

In this case, another technique can be used called context API. It’s ideal when you want to let multiple components communicate with descendants, but you don’t want to pass props around.

The context API is provided by 2 functions which are provided by the svelte package: getContext and setContext.

You set an object in the context, associating it to a key:

<script>
import { setContext } from 'svelte'

const someObject = {}

setContext('someKey', someObject)
</script>

In another component you can use getContext to retrieve the object assigned to a key:

<script>
import { getContext } from 'svelte'

const someObject = getContext('someKey')
</script>

You can only use getContext to retrieve a key either in the component that used setContext or in one of its descendants.

If you want to let two components living in 2 different component trees communicate there’s another tool for us: stores.

Leave a comment

Your email address will not be published. Required fields are marked *