Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 87 ยท State Management

Sharing State Between Components

Learn how to share state between Vue components - lifting state up, shared reactive modules and provide/inject - and when a store like Pinia is worth it.

Every non-trivial Vue app reaches the same question: who owns this piece of data? A search box needs its text. A shopping cart needs its items, but so do the header badge, the checkout page and the "recently added" toast. When two components must see the same data, you have to decide where it lives and how the others reach it.

Vue gives you several ways to answer, from simple to heavy. This lesson walks up the ladder: keep state local, lift it to a common parent, move it into a shared reactive module, scope it with provide/inject, and finally decide when a dedicated store is worth the extra structure. The key skill is picking the simplest option that works.

Start local

State that only one component uses belongs inside that component: whether a dropdown is open, the text in an input, the current tab. Putting it anywhere else makes the app harder to follow. Most state in a healthy Vue app is local, so do not reach for shared state until a second component genuinely needs the data.

Lifting state up

When two sibling components need the same data, move it into their nearest common parent. The parent owns the state, passes it down through props, and children ask for changes by emitting events up. The parent stays the single source of truth.

flowchart TD
  P["App<br/>owns items"] -->|"props: products"| L["ProductList"]
  P -->|"props: count"| B["CartBadge"]
  P -->|"props: items"| C["CartList"]
  L -.->|"emit add"| P
  C -.->|"emit remove"| P

Data flows down as props, change requests flow up as events, and one component owns the state.

In this example the product list does not know the cart exists. It only announces that someone wants a product. The parent updates the cart, and the badge and the cart list re-render because their props changed.

Lifting the cart into the parent

Add a notebook twice and a pen once: the badge shows Cart: 3 and the total is 10 USD. Everything that reads the cart updates, and there is exactly one place where the cart can change: the add and remove functions in the parent.

Lifting state is the right default. It breaks down only when the components are far apart in the tree.

Prop drilling

Suppose the cart badge lives in the header, and the add button is five levels down inside a product card. Lifting the state to App means passing items through every component in between, even those that do not care about it. This is called prop drilling. It is tolerable for two levels and painful for five, because every intermediate component must declare and forward props it never uses.

You then have two ways out: move the state out of the component tree entirely (a shared module), or let a parent offer it to all its descendants without passing it explicitly (provide/inject).

A shared reactive module

A Vue reactive object does not care where it was created. If you create one at the top level of a JavaScript module and import it from several components, they all see the same object, and because it is reactive, every component that read from it re-renders when it changes. No parent-child relationship is required.

JavaScript
// stores/cart.js
import { reactive, computed } from "vue";

export const cart = reactive({ items: [] });

export const count = computed(() => cart.items.reduce((sum, item) => sum + item.qty, 0));

export function addToCart(product) {
  const existing = cart.items.find((item) => item.id === product.id);
  if (existing) {
    existing.qty++;
  } else {
    cart.items.push({ ...product, qty: 1 });
  }
}

Any component can then import { cart, count, addToCart } from "../stores/cart.js" and use them. In the live editor everything is one file, so the module is represented by top-level declarations. To prove that sharing does not depend on the component tree, the next example mounts two completely separate Vue apps that know nothing about each other, and they still stay in sync.

Two separate apps sharing one reactive module

Click the buttons in the top box and the bottom box updates immediately. Both apps import the same cart object, so they depend on the same reactive data. This is the entire idea behind most "store" libraries.

The catches

A shared module is wonderfully simple, but it has trade-offs:

  • Everything is a singleton. There is exactly one cart for the whole page. That is perfect for "the logged-in user" and wrong for "the state of this particular widget," because ten widgets would share one state.
  • Anyone can change it from anywhere. Any component can write cart.items = []. With ten components doing that, it becomes hard to see why the state changed. A common fix is to export only reads and actions, which the next lesson builds.
  • Server rendering leaks state. On a server, module-level state lives as long as the process, so it would be shared between different visitors' requests. Apps rendered on the server must create their state per request. See Server-Side Rendering and Hydration.
  • Tests need a reset. State survives between tests unless you clear it.
  • Less tooling help. Libraries such as Pinia add DevTools inspection, time travel, hot reloading and a standard layout on top of the same reactive core.

Provide and inject

Provide and Inject offers a middle path: a component calls provide() to make a value available to all of its descendants, and any descendant calls inject() to receive it, however deep it sits. No intermediate component is involved, so there is no drilling, yet the state is scoped to a subtree instead of being global.

JavaScript
const COUNTER = Symbol("counter");

function provideCounter(start) {
  const count = ref(start);
  provide(COUNTER, { count, inc: () => count.value++, dec: () => count.value-- });
}
const useCounter = () => inject(COUNTER);

The example below puts the same panel on the page twice. Each panel provides its own counter, and its two children inject it. The panels never interfere with each other, which a module-level singleton could not do.

Scoped state with provide and inject

Notice that Wrapper knows nothing about counters, yet CounterDisplay inside it gets the state. Press the buttons in one panel and only that panel changes: panel one starts at 0, panel two at 100, and each has its own state.

Provide/inject has its own drawbacks: the connection is implicit (a component's behavior depends on an ancestor you cannot see in its props), and a component that injects something cannot work without the matching provider. Use a Symbol key and a small useX() function, as above, so there is one obvious place that documents the dependency.

Which one should you use?

flowchart TD
  A["Who needs the state?"] --> B["One component"]
  A --> C["A parent and a few children"]
  A --> D["A whole subtree, deep inside"]
  A --> E["Unrelated parts of the app"]
  B --> B1["Local ref or reactive"]
  C --> C1["Lift to the parent<br/>props down, events up"]
  D --> D1["provide / inject<br/>scoped to the subtree"]
  E --> E1["Shared reactive module<br/>or a store like Pinia"]

Choose the narrowest scope that fits; move up one step only when the current one hurts.

A short rule of thumb:

Situation Reach for
Only one component uses it Local state
Siblings share it, one or two levels apart Lift to the common parent
Many deep descendants need it, state is per-subtree provide / inject
One global instance used across the app (user, cart, theme) Shared module, then a store
Many actions, DevTools, SSR, tests, a team A store library such as Pinia

When a store is worth it

Move from a shared module to a structured store when these start to show up: several components modify the same state and you lose track of who changed what, you need to debug state over time, you render on the server, or you want a consistent convention for a whole team. A store is not a different kind of state. It is the shared module plus rules: state in one place, getters for derived values, and actions as the only way to change it. Building a Simple Store shows that structure with plain Vue, and Pinia is the official library built on the same idea.

Do not put everything in a global store out of habit. Putting a modal's open flag or a form field into a global store creates distance between a value and the only component that uses it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two sibling components need the same data and live one level below a common parent. What is usually the best approach?

    Lifting state keeps one source of truth with no extra machinery. Move to heavier tools only when the components are far apart or the passing becomes painful.
  2. 2. Why can two separate Vue apps share one reactive module and still stay in sync?

    A reactive object is just a Proxy over data. Anything that reads it, from any component or app, is tracked and updates on change.
  3. 3. What is a key weakness of module-level shared state on a server-rendered app?

    On the server the module is loaded once, so module-level state leaks between requests. Server-rendered apps must create state per request.
  4. 4. How is provide/inject state different from a shared module?

    Each provider supplies state to its own descendants. Two providers give two independent states, while a module singleton gives exactly one for the whole page.

Summary

  • Keep state in the component that uses it; share only when a second component truly needs it.
  • Lifting state up to a common parent (props down, events up) is the default for nearby components.
  • Prop drilling is the pain of passing props through many layers that do not use them.
  • A reactive object exported from a module is shared by every component that imports it, even across separate apps.
  • Module state is a singleton: it is global, open to mutation from anywhere and unsafe for per-request state on the server.
  • provide / inject shares state with a whole subtree and keeps instances independent, at the cost of implicit dependencies.
  • A store is a shared module plus structure (state, getters, actions); adopt one when change tracking, DevTools, SSR or team consistency matter.

Next, add that structure yourself: Building a Simple Store.