← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 2 of 7

provide/inject

provide lets an ancestor offer data that any descendant can inject, skipping the props in between.

In this page:

  1. provide/inject
Syntax
markup
// ancestor
provide() {
  return { key: value };
}

// descendant
inject: ['key']

provide/inject

An ancestor calls provide("key", value) and any deeper component calls inject("key"). It avoids prop drilling through many layers.

To keep it reactive, provide a ref or reactive object, and consider providing functions to change it.

App-level provide makes values available everywhere.

Note: Use symbols as keys in libraries to avoid name clashes.

Example: provide/inject

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <theme-panel></theme-panel>
</div>
<script>
  const app = Vue.createApp({
    setup() {
      const theme = Vue.ref("dark");
      Vue.provide("theme", theme);
      Vue.provide("toggle", () => { theme.value = theme.value === "dark" ? "light" : "dark"; });
      return {};
    },
  });
  app.component("theme-panel", { template: "<div><theme-label></theme-label></div>" });
  app.component("theme-label", {
    setup() { return { theme: Vue.inject("theme"), toggle: Vue.inject("toggle") }; },
    template: '<p>Theme: {{ theme }} <button @click="toggle">Toggle</button></p>',
  });
  app.mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Theme: light Toggle
console: Theme: light Toggle
-->
Live Example
Related Topics
Common Mistakes
  1. Providing plain values and expecting reactivity
  2. Overusing provide/inject for everything
  3. Mutating injected state from anywhere
Chapter Summary
  • provide offers, inject receives
  • Skips intermediate props
  • Provide refs to stay reactive
  • Do not overuse it
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.