0
0
Svelteframework~5 mins

Store contract (subscribe method) in Svelte

Choose your learning style9 modes available
Introduction

The subscribe method lets you watch for changes in a Svelte store. It helps your app update automatically when data changes.

You want to show live data that updates when the store changes.
You need to run code whenever the store value changes.
You want to connect a component to a shared state in your app.
You want to clean up listeners when a component is removed.
Syntax
Svelte
const unsubscribe = store.subscribe(callback);

// Later, to stop listening:
unsubscribe();

The callback runs immediately with the current store value.

Calling unsubscribe() stops updates and frees resources.

Examples
This logs the current count and updates whenever it changes.
Svelte
import { writable } from 'svelte/store';

const count = writable(0);

const unsubscribe = count.subscribe(value => {
  console.log('Count is', value);
});
Subscribe without saving unsubscribe if you don't need to stop listening manually.
Svelte
count.subscribe(value => {
  // Update UI or run code with new value
});
Always call unsubscribe() when you no longer need updates to avoid memory leaks.
Svelte
const unsubscribe = store.subscribe(value => {
  // do something
});

// Later
unsubscribe();
Sample Program

This example shows how subscribing logs the store value changes. After calling unsubscribe(), changes no longer trigger the callback.

Svelte
import { writable } from 'svelte/store';

// Create a writable store with initial value 10
const score = writable(10);

// Subscribe to changes
const unsubscribe = score.subscribe(value => {
  console.log(`Score changed to: ${value}`);
});

// Change the store value
score.set(20);
score.update(n => n + 5);

// Stop listening
unsubscribe();

// Change after unsubscribe won't log
score.set(50);
OutputSuccess
Important Notes

The subscribe callback runs right away with the current value.

Always unsubscribe when your component unmounts to avoid memory leaks.

Writable stores have set and update methods to change values.

Summary

subscribe lets you watch store changes and react immediately.

It returns an unsubscribe function to stop listening.

Use it to keep your UI or logic in sync with shared data.