Provide and inject

Intermediate · 3 min

Passing data to deeply nested components without prop drilling: reactive provided values, readonly guards, Symbol keys, and how it compares to React context.

Before thisComponents and props

LearnVue · 3 min

Provide and inject

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by LearnVueReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Prop drilling is passing a prop through components that don't use it, just so a deeper one can. `provide` and `inject` let an ancestor make a value available to its whole subtree directly.
  • `provide(key, value)` in an ancestor and `inject(key, defaultValue)` in any descendant connect through the key. The nearest ancestor that provides that key wins.
  • Providing a `ref` or `reactive` object keeps the connection live. Providing `count.value` hands over a frozen snapshot.
  • Keep mutations in the provider. Expose state with `readonly()` and provide functions that change it, so the data has one owner even when many components read it.
  • In larger apps and libraries, use exported `Symbol` keys (typed as `InjectionKey` in TypeScript) instead of strings, so two providers can't collide.
  • `inject` must run synchronously during setup. `app.provide` makes a value available to every component, which is how plugins such as Vue Router expose themselves.

The problem: prop drilling

App holds the signed-in user. A UserAvatar five components down needs it. With props alone, every component in between declares a user prop and passes it on: Layout, Sidebar, NavMenu, NavItem. None of them use it. They are just carrying it.

This is called prop drilling. It’s tolerable for one value through two levels. Past that it couples every intermediate component to data it doesn’t care about, and renaming the prop means editing five files. Think of it like an office passing a memo hand to hand down a corridor when it could go on the noticeboard everyone on that floor can read.

provide and inject are the noticeboard. An ancestor provides a value; any descendant, at any depth, can inject it.

The basic pair

The ancestor provides under a key:

<!-- App.vue -->
<script setup>
import { ref, provide } from 'vue'

const user = ref({ name: 'Ada', avatar: '/ada.png' })
provide('user', user)
</script>

Any descendant injects with the same key:

<!-- UserAvatar.vue -->
<script setup>
import { inject } from 'vue'

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

<template>
  <img :src="user.avatar" :alt="user.name" />
</template>

The components in between don’t change at all. A few rules:

  • The key can be a string or a Symbol. One component can call provide several times with different keys.
  • When several ancestors provide the same key, the nearest one wins. A nested section can override a value for its own subtree.
  • If nothing provides the key, inject returns undefined and Vue logs a warning in development.

Default values

A second argument to inject is the fallback when no ancestor provides the key:

const theme = inject('theme', 'light')

If the default is expensive to build, or is an object that shouldn’t be shared, pass a factory and true as the third argument so it is only created when needed:

const cache = inject('cache', () => new Map(), true)

Defaults make a component usable outside its usual provider, in a test for example.

Keeping it reactive

What you provide is exactly what you get. Provide a ref and the descendant gets the same ref, so it stays live. Provide a plain value and it is frozen at that moment:

const count = ref(0)

provide('count', count)        // live: descendants see every change
provide('countNow', count.value) // a snapshot of 0, forever

This catches people the same way losing reactivity does elsewhere. Unwrapping with .value before handing a value off breaks the connection. In templates the injected ref auto-unwraps, so {{ count }} works. In script, read count.value.

One owner, many readers

Once a ref is shared across a subtree, any descendant could write to it. That brings back the problem one-way props were meant to solve: when a value changes unexpectedly, every injector is a suspect. The Vue docs recommend keeping mutations in the provider:

<!-- CartProvider.vue -->
<script setup>
import { ref, provide, readonly } from 'vue'

const items = ref([])

function addItem(product) {
  items.value.push(product)
}

provide('cart', {
  items: readonly(items),
  addItem,
})
</script>

<template>
  <slot />
</template>
// Any descendant
const { items, addItem } = inject('cart')
addItem(product)       // fine
items.value.push(x)    // warning: target is readonly

Descendants read reactively and change state only through the functions the provider chose to expose. This “state plus actions” shape is the same idea a Pinia store formalises.

Symbol keys

String keys are fine in a small app. In a large one, or in a library, two unrelated providers can both pick 'config' and silently shadow each other. A Symbol is unique by construction, as covered in symbols, so the usual pattern is to export keys from one file:

// keys.ts
import type { InjectionKey, Ref } from 'vue'

export interface Cart {
  items: Readonly<Ref<readonly Product[]>>
  addItem: (p: Product) => void
}

export const cartKey: InjectionKey<Cart> = Symbol('cart')

provide(cartKey, ...) is now type-checked against Cart, and inject(cartKey) returns Cart | undefined. Typing in depth is in TypeScript with Vue.

Where you can call it, and app-level provide

inject must be called synchronously during component setup: at the top level of <script setup>, not inside a setTimeout, an event handler, or after an await. It looks up the component that is currently being set up, and outside setup there isn’t one. Composables that call inject inherit the same rule, covered in composables.

A value can also be provided to the whole app:

// main.js
const app = createApp(App)
app.provide('apiBase', 'https://api.example.com')

This is how plugins expose themselves. useRouter() from Vue Router is an inject call on a key the router plugin provided at the app level.

Compared with React context

React solves the same problem with context: createContext, a <Provider value={...}> wrapping the subtree, and useContext to read it, covered in context and avoiding prop drilling. The shape is the same: nearest provider wins, defaults for when there isn’t one. The difference is in updates. When a React context value changes, every component reading that context re-renders. In Vue, providing a ref means only the components that actually read the changed value re-render, through normal reactivity tracking. React apps often split contexts or memoize values for performance. Vue apps rarely need to.

When to use it, and when not to

Provide/inject fits state that belongs to one branch of the tree: a form and its fields, a tabs component and its panels, a theme for one section. It is also how compound components share state without the user wiring props between them. For state that is truly global or shared across unrelated parts of the app, a store gives you devtools, plugins, and a clearer home, as discussed in when you need a store. And for one prop through one or two levels, a plain prop is still the clearest option.

What the video covers

LearnVue’s three-minute video is a focused introduction: the prop-drilling problem, providing from an ancestor, and injecting in a descendant with the Composition API. It is short by design and doesn’t cover reactivity pitfalls, readonly() with update functions, Symbol keys, app-level provide, or the setup-only rule, all covered above. Lachlan Miller’s video compares provide/inject with other ways to avoid prop drilling across Vue and React. Alex Riviere’s VueConf Toronto talk goes deep on using provide/inject for shared state, framed against Vuex, which Pinia has since replaced.

Check yourself

  1. 01A `theme` value lives in `App` and is only used by a `ThemeToggle` four levels down. What's wrong with passing it as a prop, and how does provide/inject change that?

    Every component in between has to declare and forward a prop it doesn't use, which couples them to data they don't care about and makes refactoring painful. With `provide('theme', theme)` in `App` and `inject('theme')` in `ThemeToggle`, the middle components stay untouched and the value goes directly to the component that needs it.

  2. 02A parent runs `provide('count', count.value)` where `count` is a ref. Why doesn't the injecting child update when `count` changes?

    `count.value` is evaluated once, so the plain number at that moment is provided, not the reactive ref. Provide the ref itself, `provide('count', count)`, and the descendant receives the ref and stays in sync.

  3. 03Why would a provider wrap a value in `readonly()` and also provide an update function?

    So the provider stays the only place that changes the state. Descendants can read the value reactively but get a warning if they try to mutate it; to change it they call the provided function, such as `increment()`. Every change is easy to trace back to one component, which is the same reasoning as one-way props.

  4. 04When should you reach for Pinia instead of provide/inject?

    When the state is truly global rather than scoped to one subtree, when unrelated parts of the app need it, or when you want devtools inspection, plugins, and SSR-safe stores. Provide/inject is best for state that belongs to a particular branch of the tree, such as a form and its fields, or a tabs component and its tab panels.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark