Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Stores and State

Subscribing to State Changes

Learn how to react to every change of a Pinia store with $subscribe, read the mutation type and payload, choose flush and detached options, and know when watch is better.

Sometimes you want code to run whenever a store changes: log an event, save a draft, update a counter in the page title. Pinia gives you store.$subscribe() for this. It is like Vue's watch, but it fires once per mutation and tells you what kind of mutation happened.

The basic call

$subscribe takes a callback. Pinia calls it with the mutation info and the new state:

JavaScript
const cart = useCartStore();

const stop = cart.$subscribe((mutation, state) => {
  console.log(mutation.type, mutation.storeId, state.items.length);
});

// later: stop();

The return value is a function that removes the subscription.

The mutation object has these fields:

Field Meaning
type "direct" (plain assignment or push), "patch object" or "patch function" (from $patch)
storeId the id of the store, for example "cart"
payload the object passed to $patch, only for "patch object"

state is the store's whole (reactive) state, so you do not need to read it from the store again.

flowchart LR
    A["Component writes<br/>store.count++"] --> B["Pinia detects the change"]
    B --> C["$subscribe callback<br/>(mutation, state)"]
    D["store.$patch(...)"] --> B

Direct writes and $patch calls both end up in the same subscription.

Try it: a change log

The log below records the type of every mutation. Click the three buttons and compare. Notice that the subscription uses flush: "sync" so that each direct change is reported separately, which makes the types easy to see (the next section explains why).

Logging every mutation

The flush option

By default, Pinia batches subscription calls: if you change three properties in the same tick, the callback runs once after all of them, in the same way Vue batches component updates. Pass { flush: "sync" } to be called immediately after every single change instead. The other values are "pre" and "post", with the same meaning as in Vue's watch.

Use the default unless you need to see every step. Fewer calls means less work, which matters when the callback does something expensive such as saving to a server.

Subscriptions follow the component

If you call $subscribe inside a component's setup, Pinia removes the subscription automatically when the component is unmounted. That is usually what you want, because a leftover subscription would keep running for a component that no longer exists.

To keep a subscription alive for as long as the store lives, pass detached: true:

JavaScript
cart.$subscribe(callback, { detached: true });

Detached subscriptions are right for app-wide behavior, such as saving to storage. You then own the cleanup: call the returned stop function when you no longer need it.

Example: save a draft after changes

A very common use is persistence. The sandbox of the live examples blocks localStorage, so the next demo "saves" to a plain object that stands in for storage and shows how often it is written.

Saving a draft with $subscribe

In real code you would write localStorage.setItem("draft", JSON.stringify(state)). In production you would also debounce the save, or use a plugin. The plugins chapter shows how.

$subscribe or watch?

Both react to changes, but they answer different questions.

$subscribe watch(() => store.x, ...)
Fires once per mutation (batched) when the watched value changes
Knows the mutation type yes no
Gives you whole state old and new value of one thing
Best for saving, logging, syncing the whole store reacting to one property or getter

If you care about "did the cart change in any way", use $subscribe. If you care about "did user.name change from A to B", use watch. Also, $subscribe only reports state. Getters are not state, so watch them with watch.

Common mistakes

  • Mutating state inside the callback. Changing the store from its own subscription fires the callback again and can loop forever. Guard it, or do the work in an action instead.
  • Forgetting detached. A subscription created in a component disappears when the component does. If you wanted it app-wide, create it in a place that lives longer, or detach it.
  • Expecting getters to trigger it. They do not; only state mutations do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which mutation types can $subscribe report?

    Plain writes are "direct"; $patch calls are "patch object" or "patch function".
  2. 2. What happens to a $subscribe made inside a component's setup when the component unmounts?

    Pinia ties the subscription to the component unless you pass detached: true.
  3. 3. Three properties are changed in the same tick with the default flush. How often does the callback run?

    The default flush batches changes like Vue's component updates. Use flush: "sync" to get one call per change.
  4. 4. You want to react only when one getter changes. What fits best?

    $subscribe only reports state mutations. A getter is derived, so watch it with Vue's watch.

Summary

  • store.$subscribe((mutation, state) => ...) runs after state changes and returns a stop function.
  • mutation.type is "direct", "patch object" or "patch function"; storeId names the store.
  • Calls are batched by default; use flush: "sync" for one call per change.
  • In a component the subscription is removed on unmount; use detached: true to keep it.
  • Use watch for one property or a getter, $subscribe for the whole store.

Next: Typing State with TypeScript