Readable stores let you share data that can be read but not changed directly. They help keep your app organized and safe.
Readable stores in 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.
import { readable } from 'svelte/store'; const time = readable(new Date(), (set) => { const interval = setInterval(() => { set(new Date()); }, 1000); return () => clearInterval(interval); });
import { readable } from 'svelte/store'; const greeting = readable('Hello!', () => { // no updates, so no setup needed return () => {}; });
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.
<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>
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.
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.