At the entrance of Mrs. Sri's stall there's a name sign and a light switch. Anyone inside, in the kitchen or at the table at the very back, can read the stall's name and knows whether the lights are bright or dim. Nobody has to pass the message from person to person.
provide and inject work like that name sign and those lights, but for components. They send data from one component to all of its descendants (its children, their children, and so on), however deep. There's no need to pass props through every layer in between. In Vue, the sign at the entrance is provide in App. The people inside the stall are any components below App, which only need to read the sign with inject. The stall's name and the light or dark theme are the data.
Layers of props
Here is the stall's component tree, the way components sit inside components: App holds StallHeader and MenuPage, and MenuPage holds MenuCard. The theme lives in App, but MenuCard is what uses it. With props, MenuPage has to receive theme and pass it on, even though MenuPage itself doesn't use it:
<!-- App.vue -->
<MenuPage :theme="theme" />
<!-- MenuPage.vue: only a go-between -->
<script setup>
defineProps(["theme"])
</script>
<template>
<MenuCard :theme="theme" />
</template>
Passing props through components that don't use them is called prop drilling. Two layers are fine. With five, every component in the middle has to change each time the data grows.
provide and inject
With provide, App makes the stall's name and the theme available:
<!-- App.vue -->
<script setup>
import { ref, provide } from "vue"
const theme = ref("light")
provide("stallName", "Mrs. Sri's Stall")
provide("theme", theme)
function toggleTheme() {
theme.value = theme.value === "light" ? "dark" : "light"
}
</script>
<template>
<StallHeader />
<MenuPage />
<button @click="toggleTheme">Toggle theme</button>
</template>
MenuCard, two layers below App, gets the theme with inject:
<!-- MenuCard.vue, inside MenuPage -->
<script setup>
import { inject } from "vue"
const theme = inject("theme")
</script>
<template>
<div class="card" :class="theme">Fried Rice · $15 · theme {{ theme }}</div>
</template>
provide(key, value): the key is the data's name, written as text, such as"theme". The value can be anything: text, a number, a ref, an object, a function.inject(key): searches upwards, to the parent, then the parent's parent, until it finds the first component that provides that key.MenuPagein the middle doesn't need to know anything.StallHeaderonly needsconst name = inject("stallName")to get"Mrs. Sri's Stall".- The key must match exactly, including upper and lower case:
"Theme"and"theme"are two different keys. - In a big app, the key is often a
Symbol(a built-in JavaScript value that is always unique) exported from one file, for exampleexport const themeKey = Symbol(). That way, the key can't clash with text that happens to be the same. In TypeScript, its type isInjectionKey. injectdoesn't look at its own component. IfAppwritesprovide("theme", ...)and theninject("theme")in the same script, the result isundefined.
When nothing provides it
A component's ancestors are the components above it: its parent, the parent's parent, and so on. If no ancestor provides "address", inject("address") returns undefined. The template shows it as empty, and in development mode the console writes [Vue warn]: injection "address" not found. Give a default value as the second argument to be safe:
const theme = inject("theme", "light") // "light" when nothing provides it
Provide the ref, not its contents
| What App provides | App switches the theme to dark | Can MenuCard write theme.value? |
|---|---|---|
provide("theme", theme) |
MenuCard turns dark too | yes, and it changes App's theme as well |
provide("theme", theme.value) |
MenuCard stays light | it's only text, not a ref |
provide("theme", readonly(theme)) |
MenuCard turns dark too | no, refused |
theme.value is read once when provide is called, so all that gets sent is the text "light". Text can't change, so MenuCard stays light even after App goes dark. If you send the ref, provide("theme", theme), every descendant holds the same box as App.
The problem: a provided ref can be changed by any component below App. App's data then changes, and App's code doesn't show who changed it. Wrap it in readonly(theme): descendants still follow the changes when App switches the theme, but changes they write themselves are refused. The production build shows no message at all. In development mode, the console writes [Vue warn] Set operation on key "value" failed: target is readonly. If descendants really may change the theme, provide the function that changes it too: provide("toggleTheme", toggleTheme). The data still changes inside App.
In the exercise editor
In the editor, the main component is the ancestor. Its descendant is written as an object with a setup() function, then placed with <component :is>. The return { theme } at the end of setup() lets the template of Child use theme:
provide("theme", "dark")
const Child = {
setup() {
const theme = inject("theme")
return { theme }
},
template: `<p id="theme">{{ theme }}</p>`,
}
---template---
<component :is="Child" />
The result is dark. inject goes in Child's setup(), not in the main script. In a real app, inject in the same component as provide gives undefined (see the provide and inject section), and the exercises refuse that form. The second exercise has the same shape: provide("appName", "Hyper Sheets") and provide("version", "2.0") in the main script, then inject both in Info's setup(). Info shows {{ appName }} in <h3 id="app"> and {{ version }} in <span id="ver">.
📌 Props, provide/inject, or Pinia?
- Props for one or two layers: it's clear who gives what to whom.
- provide/inject for settings read by many components at different depths: the theme, the stall's name, the language. A value for the whole app can be provided in
main.jswithapp.provide("stallName", "Mrs. Sri's Stall"). - Pinia for app state changed from many places, like the cart. Covered in the Pinia lesson.
⚠️ Why is inject giving undefined, or not following changes?
- If what you provide is
theme.value, what gets sent is a copy of the text, so the descendants never follow. Providetheme. - inject in the same component as provide gives
undefinedin a real app.providein an ancestor,injectin a descendant. - With no provider,
inject("theme")givesundefined. Write its default:inject("theme", "light"). - The keys and values must match the brief. The exercise checker reads the text on the page:
#thememust bedark,#appmust beHyper Sheets,#vermust be2.0, and your code must callprovideandinjectwith those keys. The contents of#appand#vercome through{{ }}, not typed in directly.
TL;DR: provide("theme", theme) in an ancestor (a component above) and inject("theme") in a descendant (a component below, however deep) send data through the component tree (the way components sit inside components) without prop drilling. Prop drilling means passing props through components that don't use them. inject searches upwards until it finds the first ancestor that provides the data. If nothing provides it, the result is undefined, so give a default: inject("theme", "light"). Provide the ref, not .value, so descendants follow its changes, and wrap it in readonly when descendants must not change it. inject doesn't read the provide of its own component. In the exercise editor, the descendant is written as an object with setup() and placed with <component :is>.
⚡ provide in an ancestor, inject in a descendant
Write:
// App.vue
const theme = ref("light")
provide("theme", theme)
// MenuCard.vue, inside MenuPage
const theme = inject("theme")
Meaning: provide in App sends data to all descendants of App (its children, their children, and so on), however deep. There's no need for prop drilling, which means passing props through every component in the middle. inject in MenuCard searches upwards through its ancestors (its parent, the parent's parent, and so on) until it finds the first ancestor that provides the key "theme". MenuPage, which sits between App and MenuCard, doesn't need to know anything.
⚡ When nothing provides it
Write:
const theme = inject("theme", "light") // "light" when nothing provides it
Guess first: inject("address"), but no ancestor provides "address". What's the result?
undefined. The template shows it as empty.
Meaning: The second argument of inject is a default value, used when no ancestor provides that key.
⚡ Provide the ref, not its contents
Guess first: App writes provide("theme", theme.value), then switches the theme to dark. Does MenuCard turn dark too?
No, it stays light. theme.value is read once when provide is called, so all that gets sent is the text "light".
Meaning: Send the ref, provide("theme", theme), so descendants hold the same box as App. Wrap it in readonly(theme) (read-only) when descendants must not change it.