0
0
Svelteframework~5 mins

Writable stores in Svelte

Choose your learning style9 modes available
Introduction

Writable stores let you keep and change data that your Svelte app can use anywhere. They help your app remember things and update the screen automatically.

When you want to share data between different parts of your app.
When you need to update data and have the UI change right away.
When you want to keep track of user input or selections.
When you want to save app settings that can change.
When you want to react to data changes in multiple components.
Syntax
Svelte
import { writable } from 'svelte/store';

const storeName = writable(initialValue);

// To update the store:
storeName.set(newValue);

// To update based on current value:
storeName.update(current => newValue);

writable creates a store you can read and write.

Use set to replace the value, and update to change it based on the current value.

Examples
Create a writable store named count starting at 0.
Svelte
import { writable } from 'svelte/store';

const count = writable(0);
Set the count store value to 5.
Svelte
count.set(5);
Increase the current count value by 1.
Svelte
count.update(n => n + 1);
Sample Program

This Svelte component uses a writable store count to keep track of a number. Clicking 'Increase' adds 1 to the count. Clicking 'Reset' sets it back to 0. The count value shows on the page and updates automatically.

Svelte
<script>
  import { writable } from 'svelte/store';

  const count = writable(0);

  function increment() {
    count.update(n => n + 1);
  }

  function reset() {
    count.set(0);
  }
</script>

<button on:click={increment} aria-label="Increase count">Increase</button>
<button on:click={reset} aria-label="Reset count">Reset</button>

<p>Count: {$count}</p>
OutputSuccess
Important Notes

Use the $ prefix to auto-subscribe to the store in your markup.

Writable stores are reactive: when the value changes, the UI updates automatically.

Always import writable from 'svelte/store' to create writable stores.

Summary

Writable stores hold data you can change and share in Svelte apps.

Use set to replace the value and update to change it based on current value.

Use the $ prefix to read the store value reactively in your components.