Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 87 ยท Components

Provide and Inject

Share data with deeply nested Vue components without passing props through every level. Learn provide, inject, symbol keys, readonly state, default values and the trade-offs.

Props are the normal way to pass data down: the parent gives a prop to its child, the child to its own child, and so on. That is explicit and easy to follow. But in a deep tree it becomes tiring. If a page needs to tell a button five levels down which theme to use, the four components in between must accept the theme prop and hand it on, although they never use it. This is called prop drilling.

Vue has a built-in escape hatch: provide and inject. An ancestor component provides a value, and any descendant, however deep, can inject it, without the components in between knowing anything about it. This lesson covers the two functions, why you should provide refs rather than plain values, how to protect shared state with readonly(), how to avoid key collisions with symbols, app-level provides and default values, and, importantly, when not to use the feature. It builds on Props and Events and emits, and it plays the role that context plays in React.

All live examples use template strings and the full browser build of Vue 3.5.13 from jsDelivr (it contains the template compiler). In a project with a build tool you would put each component in a .vue file, as the read-only snippets show.

Prop drilling versus provide

flowchart TB
  subgraph Drilling["Prop drilling"]
    A1["App (owns theme)"] -->|"prop"| B1["Page"]
    B1 -->|"prop"| C1["Toolbar"]
    C1 -->|"prop"| D1["ThemedButton (uses it)"]
  end
  subgraph Provide["Provide / inject"]
    A2["App: provide('theme')"] --> B2["Page"]
    B2 --> C2["Toolbar"]
    C2 --> D2["ThemedButton: inject('theme')"]
    A2 -. "value delivered directly" .-> D2
  end

With provide and inject, the components between the provider and the consumer do not need to know about the value.

The API has two functions, both called inside setup() (or <script setup>):

HTML
<!-- Provider (read-only SFC) -->
<script setup>
import { ref, provide } from 'vue'

const theme = ref('light')
provide('theme', theme)
</script>
HTML
<!-- Any descendant (read-only SFC) -->
<script setup>
import { inject } from 'vue'

const theme = inject('theme')
</script>

provide(key, value) stores the value for the current component and everything below it. inject(key) looks upward through the parent chain and returns the value from the closest ancestor that provided that key. If you provide the same key at two levels, the nearer one wins. That allows a subtree to override a value for its own children.

Provide refs, not plain values

If you provide a plain number or string, the descendant gets a copy of it, and the copy never changes. Provide a ref (or a reactive object) and the descendant receives the same reactive container, so every change is visible everywhere. To let descendants change the value, it is best to provide a function next to the ref, so that the owner stays in charge of how its state changes.

In the example, ThemedButton sits two levels below the provider. Page and Toolbar do not mention the theme at all.

A theme shared with a deeply nested button

Click the button: the state lives in the root, the button two levels down changes it through the provided function, and the root's text and colours update.

Keep shared state safe: readonly and one owner

Because any descendant can inject a ref, any descendant could also write to it, and in a large app finding the code that changed a value is painful. The convention is one owner per piece of state: the provider exposes the state wrapped in readonly() and exposes the allowed changes as functions.

Symbols as keys

A string key such as "theme" can clash: two libraries or two teams might both use "user". A symbol is a unique value, so a symbol key can never collide with anyone else's. Create it once in a shared module and import it in both the provider and the consumers. Using the key also gives you a single place to look up what is provided (and, in TypeScript, an InjectionKey<T> makes inject type-safe, see TypeScript with Vue).

sequenceDiagram
  participant K as counter-key.js (Symbol)
  participant P as Provider
  participant C as Consumer
  P->>K: import CounterKey
  C->>K: import CounterKey
  P->>P: provide(CounterKey, { count: readonly(count), increment })
  C->>P: inject(CounterKey)
  Note over C: can read count and call increment, but cannot assign count

A shared symbol is the contract between provider and consumer.

The next example combines both ideas. The Display component receives a read-only count and an increment function. It also has a button that tries to assign count.value = 100 directly. The assignment is ignored (a development build also prints a warning in the console), so the count is still correct afterwards.

A symbol key with a read-only ref

App-level provide and default values

provide can also be called on the application itself: app.provide("appName", "Notes") makes the value available to every component in the app. Plugins use this to hand their services to the whole tree (see Plugins).

inject(key, defaultValue) supplies a fallback when no ancestor provides the key, which makes a component usable on its own, for instance in a test. If the default is expensive to create, pass a function and true as the third argument: inject(key, () => makeThing(), true). Without a default, a missing key produces a warning in development and returns undefined.

app.provide and inject defaults

Options API

In the Options API, use the provide and inject options. A plain provide: { theme: "light" } is not reactive. To share reactive data, return an object from a provide() function and wrap the values in computed(), for example provide() { return { theme: computed(() => this.theme) } }. In new code the Composition API form shown above is simpler. See The Options API for the mapping.

Trade-offs: when to use it

Provide and inject make dependencies implicit. Reading the child's props tells you what it needs; reading its inject calls tells you only by searching ancestors. That is a real cost, so use the feature deliberately:

  • Good fits: theme, locale, the current user, a form's shared state for its fields, a tabs component sharing the active tab with its tab panels, plugin services.
  • Poor fits: data that belongs to one parent and one or two children, where a prop is clearer. Two levels of props is not "drilling".
  • State that many unrelated components edit: consider a shared store (Sharing State Between Components and Building a Simple Store). Provide/inject only reaches descendants, while a store module is available everywhere.
  • Always document the keys: put them in one file next to the provider, and export a small useX() helper (a composable) that wraps inject and throws a clear error if the provider is missing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component calls provide('user', name) where name is a plain string variable. A descendant injects it. What happens when name changes later in the provider?

    Plain values carry no reactivity. Provide a ref or reactive object so descendants receive the same reactive container.
  2. 2. Two ancestors both provide the key 'theme'. Which value does a descendant get from inject('theme')?

    inject walks up the parent chain and stops at the first match, so the nearest provider overrides farther ones for its subtree.
  3. 3. Why use a Symbol as an injection key?

    Strings can clash between libraries or teams. A symbol exported from one module is a unique shared contract.
  4. 4. What is the best way to stop descendants from changing provided state directly?

    A readonly proxy rejects writes, while the provided functions keep the owner in control of how the state changes.
  5. 5. A component needs a value only from its direct parent. What is usually the clearest choice?

    Props make the dependency visible in the component's API. Provide and inject are for values needed by many or deep descendants.

Summary

  • provide(key, value) makes a value available to all descendants; inject(key) finds the nearest provider above.
  • Provide refs or reactive objects, not plain values, so changes reach the consumers.
  • Keep one owner: provide readonly(state) plus update functions.
  • Use symbols as keys for collision-free contracts; inject accepts a default value or a factory (with true).
  • app.provide shares a value with the whole application.
  • The dependency is implicit, so prefer props for simple parent-child data and a store for global state.

Next, learn how to switch between components dynamically in Dynamic and Async Components.