0
0
Svelteframework~5 mins

Readable stores in Svelte

Choose your learning style9 modes available
Introduction

Readable stores let you share data that can be read but not changed directly. They help keep your app organized and safe.

When you want to share data that updates over time but should not be changed by components.
When you have data coming from an external source like a timer or a web API.
When you want to create a store that only sends updates but does not allow direct modification.
When you want to keep some state read-only for components to avoid accidental changes.
Syntax
Svelte
import { readable } from 'svelte/store';

const store = readable(initialValue, (set) => {
  // setup code here
  // call set(newValue) to update

  return () => {
    // cleanup code here
  };
});

The readable function takes two arguments: the initial value and a function to set up updates.

The setup function receives a set function to update the store value and can return a cleanup function.

Examples
This example creates a readable store that updates the current time every second.
Svelte
import { readable } from 'svelte/store';

const time = readable(new Date(), (set) => {
  const interval = setInterval(() => {
    set(new Date());
  }, 1000);

  return () => clearInterval(interval);
});
A simple readable store with a fixed value and no updates.
Svelte
import { readable } from 'svelte/store';

const greeting = readable('Hello!', () => {
  // no updates, so no setup needed
  return () => {};
});
Sample Program

This Svelte component uses a readable store named count that updates every second with the current timestamp. The component shows the live timestamp on the page.

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

  const count = readable(0, (set) => {
    const interval = setInterval(() => {
      set(Date.now());
    }, 1000);

    return () => clearInterval(interval);
  });
</script>

<main>
  <h1>Current timestamp:</h1>
  <p>{$count}</p>
</main>
OutputSuccess
Important Notes

Readable stores cannot be changed directly by components; only the setup function can update them.

Always return a cleanup function from the setup to avoid memory leaks, especially with timers or subscriptions.

Use the $ prefix in Svelte components to subscribe and get the current value automatically.

Summary

Readable stores provide read-only reactive data in Svelte.

They update values internally but prevent external changes.

Use them for data like timers, external events, or fixed values.