Svelte Stores

Svelte provides a simple yet powerful store mechanism for state management. This page demonstrates various ways to work with stores in Svelte.

Theme Store Example

Current theme: light

This box's appearance changes based on the selected theme.

// stores.js
import { writable } from 'svelte/store';

export const userPreference = writable({
  theme: 'light',
  fontSize: 16
});

// In component
import { userPreference } from './stores.js';

// Access store value with $ prefix
<p>Current theme: {$userPreference.theme}</p>

// Update store
function setTheme(theme) {
  userPreference.update(prefs => ({
    ...prefs,
    theme
  }));
}

Counter Store Examples

Global Counter Store

Current value: 0

Local Component Store

Current value: 0

Derived Store

Global + Local = 0

This value is automatically calculated from both counter stores.

// Creating stores
const count = writable(0);
const derivedCount = derived(
  [countStore, localCount],
  ([$countStore, $localCount]) => $countStore + $localCount
);

// Using stores
<p>Count: {$count}</p>

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

function reset() {
  count.set(0);
}

Readable Store Example

Time Store

2:18:07 PM

12/8/2025

// Creating a readable store
const time = readable(new Date(), function start(set) {
  const interval = setInterval(() => {
    set(new Date());
  }, 1000);
  
  return function stop() {
    clearInterval(interval);
  };
});

// Creating a derived store
const formattedTime = derived(
  time,
  $time => $time.toLocaleTimeString()
);

// Using the store
<p>{$formattedTime}</p>

Custom Store Example

Creating Custom Stores

Custom stores let you create your own store with tailored methods. Check the code example below to see how you can create one:

// Custom store example
function createCountStore() {
  const { subscribe, set, update } = writable(0);
  
  return {
    subscribe,
    increment: () => update(n => n + 1),
    decrement: () => update(n => n - 1),
    reset: () => set(0)
  };
}

export const count = createCountStore();

// Usage in component
import { count } from './stores.js';

// Now you can use methods directly
<button on:click={count.increment}>+</button>