Vue Provide / Inject

Vue Provide / Inject
What is Provide / Inject?
provide→ Parent provides datainject→ Child injects (receives) dataWorks across any depth (parent → grandchild → great-grandchild)
Ideal when many nested components need the same data.
Why Use Provide / Inject?
Problem (Prop Drilling)
Passing props through many layers:
Solution (Provide / Inject)
Parent provides once, children inject directly.
Basic Example (Options API)
Parent Component
Child / Grandchild Component
Output
Provide / Inject with Reactive Data (Important)
Not reactive by default
count will NOT update in child.
Making Provide / Inject Reactive (Vue 3)
Using ref / reactive
Injecting
- Reactive updates work correctly
Provide / Inject in Composition API
Parent
Child
Default Value in Inject
- Prevents errors if
provideis missing.
Using Symbols (Best Practice)
Avoid name conflicts using Symbol.
Provide
Inject
- Safer & scalable for large apps
When to Use Provide / Inject
- Global config (theme, language)
- Plugin data
- UI libraries
- Dependency injection
Not ideal for:
Frequent state changes (use Pinia/Vuex)
Simple parent-child (use props)
Provide / Inject vs Props
| Feature | Props | Provide / Inject |
|---|---|---|
| Parent → Child | Yes | Yes |
| Deep nesting | Hard | Easy |
| Explicit | Yes | Hidden |
| Reactivity | Yes | Manual |
Interview Questions (Vue Provide / Inject)
Q1. Is provide/inject reactive by default?
No
Q2. When should we use provide/inject?
To avoid prop drilling
Q3. Difference between props and inject?
Props are explicit, inject is implicit
Q4. Best alternative for shared state?
Pinia / Vuex
Summary
provideshares datainjectreceives data- Avoids prop drilling
- Not reactive by default
- Reactive with
ref/reactive Best for global/deep dependencies
