Using the Context API in Svelte

Introduction to Context API

In this lesson, we’ll explore Svelte’s Context API, a powerful tool for sharing data across components without the need to pass props through every level of your component tree. This is especially useful in larger applications where components are deeply nested, and passing data via props becomes cumbersome.

So far in this course, you’ve learned how to handle user interactions, pass data with props, use callback functions for parent-child communication, and implement two-way binding. These techniques are essential for managing data flow in Svelte applications. However, when dealing with deeply nested components, prop drilling (passing props through multiple layers) can make your code harder to maintain.

The Context API solves this problem by allowing you to share data globally within a specific part of your component tree. Think of it as a shared workspace where components can access the same data without explicitly passing it down. For example, you might use the Context API to share a theme (like "dark" or "light") across multiple components without manually passing the theme prop to each one.

In this lesson, you’ll learn how to use the Context API to share and access data efficiently. Let’s dive in!

Setting Up Context

To share data using the Context API, you’ll use the setContext function. This function allows you to define a key-value pair that can be accessed by any child component within the same tree.

Here’s an example of how to set up context in a parent component:

Svelte
<!-- Parent.svelte -->
<script>
  import { setContext } from 'svelte';
  setContext("theme", "dark");
</script>

{@render children()}

In this example, we’re setting a context with the key "theme" and the value "dark". Any child component within this tree can now access the "theme" context.

Accessing Context

To access the shared context in a child component, you’ll use the getContext function. This function retrieves the value associated with a specific key from the context.

Here’s how you can access the "theme" context in a child component:

<!-- Child.svelte -->
<script>
  import { getContext } from 'svelte';
  let theme = getContext("theme");
</script>

<p>Current Theme: {theme}</p>

In this example, the getContext("theme") function retrieves the value "dark" that was set in the parent component. The theme variable is then used to display the current theme in a paragraph element.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal