What is a state in Svelte?

Like useState in React, Svelte is a framework that is used to develop front end applications.

What exactly is a state? A state stores the current form of data in the application and then changes it according to how the programmer wants it to change. For example, a website can have a state named isSignedIn. It would be set to true if the user is signed in and false otherwise.

How to get and set state

To read and to set state, Svelte provides support. Use the following statements to import it.

import { setContext } from 'svelte'

import { getContext } from 'svelte'

This library controls your state within those components.

Code

The following code implements the example we discussed earlier about how to manage the user’s login status with isSignedIn.

<script>
import { setContext } from 'svelte'
import { getContext } from 'svelte'
const signedIn = false
setContext('isSignedIn', signedIn) //initial state set
function SignIn(){
const currentState = getContext('isSignedIn')
if (currentState === false){
setContext('isSignedIn', true)
callSignIn(email, password); //calls the external signin function to sign in by using email and password.
}
else {
alert("You are already signed in");
}
}
//Supposing that a sign in button calls the above function
</script>
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
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources