What is the provide/inject pattern in Vue?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Vue.js development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
provide/inject allows an ancestor component to provide data/functions that any descendant component can inject, without prop drilling (passing through every intermediate component). Provider (ancestor): import { provide, ref } from "vue"; const theme = ref("dark"); const toggleTheme = () => { theme.value = theme.value === "dark" ? "light" : "dark"; }; provide("theme", { theme, toggleTheme });. Consumer (any descendant): import { inject } from "vue"; const { theme, toggleTheme } = inject("theme");. Default value: inject("theme", "light") — if no provider found. App-level provide: app.provide("globalConfig", config) — available everywhere. Reactivity: to keep reactivity when injecting, provide refs or reactive objects (not raw values). If the consumer modifies the provided value, it affects the provider — to prevent this, provide a readonly wrapper: provide("count", readonly(count)). Symbol keys: use Symbol instead of strings to avoid naming collisions: export const themeKey = Symbol("theme"); provide(themeKey, theme);. vs Pinia/Vuex: provide/inject is for implicit dependency injection for component libraries (like passing a form context from parent form to nested field components). Pinia/Vuex is better for complex global application state. Vue Router and Pinia themselves use provide/inject under the hood.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.