How to use context in Svelte

Introduction

Let’s say we have three components, A, B, and C, and we want to define a variable or object in Component A, but we also want it to be accessible from Component C.

In this shot, we’ll discuss the context method in Svelte.

getContext and setContext

Svelte passes parent component data to its child components. The getContext and setContext functions can access associated data with a key on the context. Changes made to context values are only valid for the current child component; parent component values remain intact.

Let’s say a user logs in and we want to show the user details (the email and login status) in another component. In this scenario, we’ll want to use the Context API instead of passing the props.

Code

<script>
import { setContext } from 'svelte'
const userDetails = { username: 'abc@example.com', islogin: 'yes' };
setContext('user-details', userDetails )
import ContextComponent from "./ContextComponent.svelte";
</script>
<main>
<p> Context Example. </p>
<hr/>
<div>
<br />
<ContextComponent />
</div>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>

The setContext function

If we check the setContext{} function, we’ll see something similar to export declare function setContext<T>(key: any, context: T): void;.

The setContext function accept two arguments:

  • Context key
  • The value, variable, or object that we want to send to all of the child application components

In the code above, we set the context key as user-details and pass userDetails object as the second argument.

The getContext function

Svelte provides the getContext function to retrieve the setContext key. Create another component ContextComponent.svelte and add the following code:

<script>
import { getContext } from 'svelte'
const userDetails = getContext('user-details')
</script>
<div>
<div>
<strong>User Name:</strong> { userDetails.username }
</div>
<div>
<strong>User Login Status:</strong> { userDetails.islogin }
</div>
</div>

We define the getContext function as export declare function getContext<T>(key: any): T; in Svelte.

The getContext function only accepts one argument (key). In this case, we define the key in our App component (user-details).

If you go to the web page, it should look like the image below.

widget
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources