Provide/Inject — Vue

provide("theme", theme) in an ancestor (a component above) and inject("theme") in a descendant (a component below, however deep) send data through the…

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>

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?

⚠️ Why is inject giving undefined, or not following changes?

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.

What you will learn