Svelte logo

Svelte by Example: Readable Stores

A readable store is a store that can be subscribed to, but not updated from a component. Readable stores are useful for subscribing to external data.

In this example, we'll create a readable store that updates when the user's preferred color scheme changes.

Svelte exposes a readable function to create readable stores.

Readable accepts two arguments. The first is the default value for the store. The second a start function to keep the value up to date.

When a component subscribes to the store, it will execute the start function. We'll listen for media query changes here.

The start function must return a stop function. The stop function will be executed when no more components are subscribed to the store.

The current store value can be retrieved with $.

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

const mediaQueryList = window
  .matchMedia('(prefers-color-scheme: dark)');

export const theme = readable(
  mediaQueryList.matches ? 'dark' : 'light';,
  function(set) {
    function listener(query) {
      set(query.matches ? 'dark' : 'light');
    }

    mediaQueryList.addEventListener(
      'change',
      listener,
    );

    return () => {
      mediaQueryList.removeEventListener(
        'change',
        listener,
      );
    };
  }
);
Page.svelte
<script>
  import { theme } from './stores.js';
</script>

<section class:dark={$theme === 'dark'}>
  <!-- … -->
</section>