provide and inject pass values to deep descendants without prop drilling—Vue’s alternative to React Context.
Basic pattern
// ancestor setup
provide('theme', theme);
// descendant setup
const theme = inject('theme');
Use injection keys as symbols or strings consistently. Prefer readonly injected state when children should not mutate global theme directly.
When to use
- Theme, locale, or density tokens
- Authenticated user snapshot for deeply nested nav
- Feature flags or form wizard context
When to avoid
Do not replace every prop with inject—explicit props document a component’s contract. Reach for provide/inject when intermediate layers should not know about the data.
Important interview questions and answers
- Q: provide/inject vs props?
A: Props are explicit per level; inject skips intermediate components for cross-cutting concerns. - Q: React Context equivalent?
A: Similar purpose; Vue uses function calls instead of Context.Provider JSX.
Self-check
- Which component calls
provide? - Why use a Symbol as the injection key?
Pitfall: Providing a new object literal every render re-triggers inject consumers—provide stable refs or computed values.
Interview prep
- When use provide/inject vs props?
When deeply nested descendants need a shared value (theme, locale) without passing props through every intermediate layout shell.