What is provide/inject in Vue, and when do you use it?

Vue.js Components Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

provide lets an ancestor component expose a value that any descendant can inject, no matter how deep — avoiding “prop drilling” through intermediate components that don't care about the value. Good for a theme, a form context, or a plugin's API.

Provide/inject lets a component higher up the tree make a value available to any component below it, however many levels down, without passing it as a prop through every component in between. That's the prop-drilling problem it solves. I use it for things like a theme, or a form component providing context that its field components inject. If I provide a ref it stays reactive. The line versus a store is that provide/inject is scoped to one subtree and is great for component libraries, whereas a Pinia store is for genuinely global state.

  • Provide a ref/reactive value to keep it reactive in descendants; provide a plain value and it's static.
  • Also provide functions so descendants can update the shared state (keep mutations in the provider).
  • provide/inject vs a store: provide/inject is scoped to a subtree and great for component libraries and localized context; a Pinia store is for app-wide state.
  • Overuse makes data flow implicit and hard to trace.