Svelte stores

Svelte stores are a great tool to handle your app state when components need to talk to each other without passing props around too much.

You must first import writable from svelte/store:

import { writable } from 'svelte/store'

and create a store variable using the writable() function, passing the default value as the first argument:

const username = writable('Guest')

This can be put into a separate file which you can import into multiple components, for example, called store.js (it’s not a component, so it can be in a .js file instead of .svelte):

import { writable } from 'svelte/store'
export const username = writable('Guest')

Any other component now loading this file can access the store:

<script>
import { username } from './store.js'
</script>

Now the value of this variable can be set to a new value using set(), passing the new value as the first argument:

username.set('new username')

And it can be updated using the update() function, which differs from set() because you don’t just pass the new value to it – you run a callback function that is passed the current value as its argument:

const newUsername = 'new username!'
username.update(existing => newUsername)

You can add more logic here:

username.update(existing => {
  console.log(`Updating username from ${existing} to ${newUsername}`)
  return newUsername
})

To get the value of the store variable once, you can use the get() function exported by svelte/store:

import { writable, get } from 'svelte/store'
export const username = writable('Guest')
get(username) //'Guest'

To create a reactive variable that’s updated whenever the store value changes instead, you can prepend the store variable using $ (in this example $username). Using that will make the component re-render whenever the stored value changes.

Svelte considers $ to be a reserved value and will prevent you from using it for things that are not related to stores values (which might lead to confusion). So if you are used to prepending DOM references using $, don’t do it in Svelte.

Another option, best suited if you need to execute some logic when the variable changes, is to use the subscribe() method of username:

username.subscribe(newValue => {
  console.log(newValue)
})

In addition to writable stores, Svelte provides 2 special kinds of stores: readable stores and derived stores.

Leave a comment

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