Vue Provide/Inject
Props work well between a parent and its direct child. But what if a value is needed five levels deep — the current user, a colour theme, a language setting? Passing it through every component in between is called prop drilling, and it's tedious: the middle components don't even use the value.
App (has theme)
└── Layout ← must pass theme
└── Sidebar ← must pass theme
└── Menu ← must pass theme
└── MenuItem (actually uses theme)Provide/inject solves this. An ancestor provides a value under a key, and any descendant, however deep, can inject it.
Basic usage
<div id="app">
<page-layout></page-layout>
</div>
<script type="module">
import { createApp, provide, inject } from 'vue';
const app = createApp({
setup() {
provide('siteName', 'TAD Market');
provide('user', { name: 'Linh', role: 'admin' });
}
});
// middle component: knows nothing about siteName or user
app.component('page-layout', {
template: `<div style="border:1px dashed #aaa;padding:8px">
<small>page-layout</small>
<user-badge></user-badge>
</div>`
});
app.component('user-badge', {
setup() {
const siteName = inject('siteName');
const user = inject('user');
const missing = inject('notProvided', 'default value');
return { siteName, user, missing };
},
template: `<p>{{ siteName }}: logged in as <b>{{ user.name }}</b> ({{ user.role }}).
Missing key → "{{ missing }}"</p>`
});
app.mount('#app');
</script>inject(key, defaultValue) returns the default when no ancestor provides the key.
Providing reactive data
A plain value is provided once and never updates. To keep injectors in sync, provide a ref or a reactive object. A good pattern is to provide the state read-only together with functions that change it, so all mutations stay in the provider.
<style>
.light { background: #fff; color: #222; }
.dark { background: #1f2937; color: #f9fafb; }
.box { padding: 10px; border-radius: 8px; margin: 6px 0; border: 1px solid #ccc; }
</style>
<div id="app">
<theme-toggle></theme-toggle>
<article-card title="Provide/inject"></article-card>
<article-card title="Prop drilling"></article-card>
</div>
<script type="module">
import { createApp, ref, readonly, provide, inject } from 'vue';
const app = createApp({
setup() {
const theme = ref('light');
const toggleTheme = () => { theme.value = theme.value === 'light' ? 'dark' : 'light'; };
provide('theme', { theme: readonly(theme), toggleTheme });
}
});
app.component('theme-toggle', {
setup() {
const { theme, toggleTheme } = inject('theme');
return { theme, toggleTheme };
},
template: `<button @click="toggleTheme">Switch to {{ theme === 'light' ? 'dark' : 'light' }} mode</button>`
});
app.component('article-card', {
props: ['title'],
setup() {
const { theme } = inject('theme');
return { theme };
},
template: `<div class="box" :class="theme"><b>{{ title }}</b> — rendered in {{ theme }} mode</div>`
});
app.mount('#app');
</script>readonly(theme) prevents children from writing theme.value = … directly. They must call toggleTheme, which keeps the logic in one place.
Options API syntax
// ancestor
export default {
data: () => ({ lang: 'en' }),
provide() {
return {
// computed() keeps it reactive when lang changes
lang: computed(() => this.lang)
};
}
};
// descendant
export default {
inject: ['lang'], // or { lang: { default: 'en' } }
template: `<p>{{ lang }}</p>`
};App-level provide
app.provide(key, value) makes a value available to every component in the app. Plugins such as Vue Router and Pinia use this internally.
<div id="app"><price-tag :amount="1999.5"></price-tag> <price-tag :amount="12"></price-tag></div>
<script type="module">
import { createApp, inject } from 'vue';
const app = createApp({});
app.provide('currency', { code: 'EUR', locale: 'de-DE' });
app.component('price-tag', {
props: ['amount'],
setup(props) {
const { code, locale } = inject('currency');
const fmt = new Intl.NumberFormat(locale, { style: 'currency', currency: code });
return { format: (n) => fmt.format(n) };
},
template: `<span style="background:#ecfdf5;padding:2px 6px">{{ format(amount) }}</span>`
});
app.mount('#app');
</script>When to use what
| Situation | Tool |
|---|---|
| Parent → direct child | Props |
| Child → parent | Emits |
| Ancestor → deep descendants in one subtree (theme, form context, tabs) | Provide / inject |
| Truly global, shared app state (cart, logged-in user) | A store (Pinia) |
Tip: In larger apps, use Symbols as keys (
export const ThemeKey = Symbol('theme')) in a shared file. String keys from different libraries could clash.
Note:
provide()andinject()must be called synchronously insidesetup()(or<script setup>). Calling them later, for example in asetTimeout, doesn't work.
Test yourself
What problem does provide/inject solve?
- Slow rendering
- Passing data through many intermediate components (prop drilling)
- Making HTTP requests
- Styling components
What does inject('lang', 'en') return if no ancestor provides lang?
undefined- An error
'en'null
Why provide readonly(state) together with update functions?
- It is faster
- So descendants can't change the state directly; changes go through the provider
- readonly makes the state reactive
- It is required by Vue