BeginnerCoder

Lesson 23 — Composable store

Shared state without a library

A composable that creates its ref inside the function gives every caller a separate copy. Move the ref outside the function (to the module level) and every caller gets the same one — a tiny store that all components share. Pinia, Vue's official store library, builds on this idea.

const user = ref(null)            // one copy for the whole app
export function useAuth() {
  return { user, logout: () => (user.value = null) }
}

Why it matters: a cart badge in the header and the cart page must show the same number.

Want it another way?
Task

Make useCounterStore use the shared ref. Two clicks should show "Shared 2" on the button and "Badge: 2" in the child.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Vue.js Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.