Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Composition and Setup Stores

Composables and Watchers in Setup Stores

Use watch, watchEffect and your own composables inside Pinia setup stores: debounced search, derived saves, reusable logic, and the limits around inject, router and SSR.

The main reason to choose a setup store is that the store becomes a normal Composition API function. Anything you can do in setup() you can do in the store: watch, watchEffect, onScopeDispose, and composables, both yours and from libraries. This lesson shows the useful patterns and the traps.

A watcher inside a store

Say the store should keep a computed "document title" in sync, or save when something changes. In an options store you would need a plugin or a component. In a setup store you just write it:

JavaScript
export const useSettingsStore = defineStore("settings", () => {
  const theme = ref("light");
  const saves = ref(0);

  watch(theme, (value) => {
    saves.value++;
    // here you would call localStorage.setItem("theme", value)
  });

  return { theme, saves };
});

The watcher lives as long as the store. Pinia runs the setup function in an effect scope, so Vue stops the watcher when the store is disposed (for example when you call store.$dispose()), without you doing anything.

A watcher that counts saves

Change the theme or the font size; each change triggers the watcher, which "saves". Real code would write to localStorage (blocked in the sandbox, so the demo only records the text it would save).

Debounce an expensive reaction

Watchers fire on every keystroke. For a search store you usually wait until the user pauses. A debounce is a small function, and in a setup store it fits naturally:

JavaScript
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

export const useSearchStore = defineStore("search", () => {
  const query = ref("");
  const results = ref([]);

  const run = debounce(async (q) => {
    results.value = q ? await api.search(q) : [];
  }, 300);

  watch(query, run);

  return { query, results };
});
A debounced search store

Type "alan" quickly: four keystrokes, but the search runs only once, 400 ms after you stop.

Write your own composable and use it in a store

A composable is a function that uses reactivity and returns refs. Extract repeated logic into one and call it from any store:

JavaScript
// useUndo.js
import { ref, computed } from "vue";

export function useUndo(source) {
  const history = ref([]);
  function save() { history.value.push(JSON.stringify(source.value)); }
  function undo() {
    const last = history.value.pop();
    if (last !== undefined) source.value = JSON.parse(last);
  }
  return { save, undo, canUndo: computed(() => history.value.length > 0) };
}
JavaScript
export const useDrawingStore = defineStore("drawing", () => {
  const shapes = ref([]);
  const { save, undo, canUndo } = useUndo(shapes);

  function addShape(shape) {
    save();
    shapes.value.push(shape);
  }

  return { shapes, addShape, undo, canUndo };
});

Rules for the return value: return shapes (state), addShape and undo (actions) and canUndo (a computed, so a getter). save stays private.

An undo composable inside a store

Libraries and composables that work

Most composables work in stores when they only use reactivity, timers and browser APIs: useLocalStorage, useDebounceFn, useMouse and so on from VueUse, plus your own. Two cautions:

  1. Browser-only APIs on the server. In server-side rendering, localStorage and window do not exist. Guard them, or see SSR and hydration later in the course for skipHydrate.
  2. State created by a composable is still state. If useLocalStorage returns a ref and you want it in $state, DevTools and SSR, return it from the store. For SSR, refs made by composables like that must be marked with skipHydrate() so Pinia does not try to replace them with server data.

Things that do not work

A setup store is not a component. It is created outside any component instance, so APIs that need one are unavailable:

  • useRoute() and useRouter() from Vue Router. Import the router instance directly instead.
  • onMounted, onUnmounted and other component lifecycle hooks. They need a component instance. Use onScopeDispose for cleanup tied to the store's scope.
  • provide()/inject() of component-level values. App-level provide values work (Pinia runs the setup with app.runWithContext), but anything provided by a parent component is invisible.
  • Calling useAttrs(), useSlots() and similar.
flowchart LR
    A["Setup store function"] --> B["ref / computed / watch"]
    A --> C["Your composables"]
    A --> D["onScopeDispose"]
    A -. "not available" .-> E["onMounted, useRoute, component inject"]

A store has an effect scope, not a component instance.

Cleaning up

If a composable starts a timer or an event listener, stop it when the store is disposed:

JavaScript
const id = setInterval(tick, 1000);
onScopeDispose(() => clearInterval(id));

Stores usually live as long as the app, so this matters mainly in tests and hot reloading, where stores are created and thrown away repeatedly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where can you call watch() as part of the store definition?

    The setup function is Composition API code, so watch, watchEffect and composables are available.
  2. 2. Which API is not available inside a setup store?

    Lifecycle hooks need a component instance. A store has an effect scope; use onScopeDispose for cleanup.
  3. 3. What should you return from a store that uses a composable's canUndo computed?

    Anything components should read must be returned. A returned computed becomes a getter.
  4. 4. Why debounce a watcher in a search store?

    Debouncing waits for a quiet period so only the final value triggers the expensive work.

Summary

  • Setup stores can use watch, watchEffect, onScopeDispose and any reactivity-based composable.
  • Debounce, undo history and storage syncing are typical store-level composables.
  • Return every state, computed and action that others need; keep helpers private.
  • Component-only APIs (onMounted, useRoute, component inject) are not available.
  • Guard browser-only code for SSR and clean up with onScopeDispose.

Next: Using Stores Outside Components