How do provide and inject work in Vue?

IntermediateVue interview questionBy , updated 17 November 2026

Short answer

provide and inject let an ancestor component share a value with all of its descendants, however deep, without passing props through every level in between. The ancestor calls provide(key, value) in its setup, and any descendant calls inject(key) to read it. The nearest provider with that key wins. If you provide a ref or reactive object, consumers stay in sync with it. It is Vue's built-in dependency injection.

The problem: prop drilling

Imagine a page that knows the current user, and a deeply nested avatar that needs it. Without injection, every component in between declares a user prop only to pass it on. That clutters intermediate components and couples them to data they do not use. Prop drilling describes the general problem; provide and inject are Vue's answer for values that belong to a subtree.

Basic usage

<!-- AccountPage.vue (ancestor) -->
<script setup>
import { ref, provide } from "vue";

const user = ref({ name: "Ada", plan: "pro" });
provide("user", user);
</script>
<!-- UserAvatar.vue (any descendant) -->
<script setup>
import { inject } from "vue";

const user = inject("user");
</script>

<template>
  <span>{{ user.name }}</span>
</template>

Both calls must run synchronously during setup. The lookup walks up the component tree, so if two ancestors provide "user", a descendant gets the closer one. A component can therefore override a value for its own subtree, for example a nested theme section.

Providing reactive values

What you provide is passed by reference. Provide the ref itself, not user.value, and every consumer sees updates. Providing user.value gives consumers a snapshot that never changes when the ref is reassigned. An injected ref is not unwrapped in script, so you read user.value there; in the template it unwraps as usual.

The Vue docs recommend keeping mutations inside the provider. If any descendant can write to shared state, bugs become hard to trace. Provide the state read-only, together with functions that change it:

// AccountPage.vue
import { ref, readonly, provide } from "vue";

const user = ref({ name: "Ada", plan: "pro" });

function upgrade(plan) {
  user.value = { ...user.value, plan };
}

provide("account", { user: readonly(user), upgrade });

readonly() returns a proxy that warns on writes in development and, with TypeScript, makes assignments a compile error. Consumers call upgrade("team") and the provider stays the single place that changes state.

Typed injection keys

String keys can collide, especially across libraries, and inject("account") is typed as unknown. Use a Symbol typed with InjectionKey<T>, exported from one file that both sides import.

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

export interface Account {
  user: Readonly<Ref<{ name: string; plan: string }>>;
  upgrade: (plan: string) => void;
}

export const accountKey = Symbol("account") as InjectionKey<Account>;
// useAccount.ts
import { inject } from "vue";
import { accountKey } from "./keys";

export function useAccount() {
  const account = inject(accountKey);
  if (!account) throw new Error("useAccount() must be used inside <AccountPage>");
  return account;
}

provide(accountKey, value) now checks that the value matches Account, and inject(accountKey) returns Account | undefined. Wrapping it in a small composable gives a clear error when the provider is missing, instead of a later undefined crash. The same pattern of composables built around injection is covered in What are composables in Vue?.

Default values

If no ancestor provides the key, inject returns undefined and logs a warning in development. Pass a default to avoid both:

const theme = inject("theme", "light");
const cache = inject("cache", () => new Map(), true); // factory: created only when needed

The third argument true tells Vue the default is a factory function to call, which avoids creating an expensive default when a provider exists, and avoids treating a function value as the default itself.

App-level provide

app.provide(key, value) makes a value available to every component in the app. This is how plugins share configuration and services.

const app = createApp(App);
app.provide("apiBase", import.meta.env.VITE_API_BASE);
app.mount("#app");

Pinia, Vue Router and many UI libraries install themselves this way. Since Vue 3.3, app.runWithContext(fn) lets code outside components, such as a router guard, call inject against the app's provides.

provide/inject vs Pinia

provide / inject Pinia
Scope A component subtree, or the app with app.provide Global to the app
Instances One per providing component, so two widgets get separate state One store instance per app
Devtools Not shown as state Inspection, time travel, action tracking
Server rendering Scoped to the component tree, so per request Per request when created per app
Typical use Compound components (Tabs and Tab, Form and Field), themes for a section, injecting services Cart, session, data many unrelated pages read and change

Use injection when the state belongs to one part of the tree, especially in reusable component libraries: each <Tabs> provides its own active tab to its own <Tab> children. Use Pinia when unrelated parts of the app share data, or when you want devtools and a clear store structure. For direct parent and child communication, plain props and emits are still clearer; see props, emits and v-model.

Practise it

Implement Vue's provide and inject: app-level providers, nearest-ancestor lookup and factory defaults builds the mechanism, which uses the prototype chain for the lookup. Build a Pinia-style defineStore shows the alternative. Build theme and settings providers practises the same scoped-override and helpful-error ideas with React context, and Build a dependency injection container covers the general pattern.

Common follow-up questions

Is provide/inject the same as React context?

Similar purpose, different mechanics. Both pass values down a tree without props. React context rerenders every consumer when the provided value changes; in Vue the provided value is usually a ref, and only code that reads it is updated through normal reactivity tracking.

Can a child provide a value back to its parent?

No. Injection only flows down. To send data up, emit an event, or provide a function from the parent that the child calls.

How does the Options API use it?

Use the provide option, as an object or a function returning one, and inject: ["key"]. To keep a provided value reactive from the Options API, provide a computed(() => this.value) instead of the raw property.

Does inject work outside setup?

Not in ordinary code: it needs the current component instance. Inside a component, call it at the top of setup. Outside components, use app.runWithContext().

Mistakes to avoid

  • Providing ref.value instead of the ref, so consumers never see updates

  • Letting any descendant mutate shared injected state instead of exposing update functions

  • Using string keys in a library where they can clash; use typed Symbol keys

  • Calling inject inside an event handler or after a timeout

  • Using injection for global app state that would be easier to inspect and test in a Pinia store

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Implement Vue's provide and inject: app-level providers, nearest-ancestor lookup and factory defaultsMedium35 min
  2. Build a Pinia-style defineStore: getters, actions, $patch, $reset, $subscribe and $onActionMedium40 min
  3. Build theme and settings providers: helpful hook errors, scoped overrides, composeProviders and stable valuesMedium35 min
  4. Build a dependency injection container: singleton, scoped and transient lifetimes, cycle paths and async disposalHard50 min