Vue Provide / Inject

Vue Tutorial

 Vue Provide / Inject

Provide / Inject is a feature of Vue.js that lets you pass data from a parent to any deep child component without prop drilling.

 What is Provide / Inject?

  • provide → Parent provides data

  • inject → Child injects (receives) data

  • Works 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:

Parent → Child → Grandchild → GreatGrandchild

Solution (Provide / Inject)
Parent provides once, children inject directly.


 Basic Example (Options API)

Parent Component

Child / Grandchild Component

Output

My Vue App

 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 provide is 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

FeaturePropsProvide / Inject
Parent → ChildYesYes
Deep nestingHardEasy
Explicit YesHidden
ReactivityYesManual

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

  • provide shares data
  • inject receives data
  • Avoids prop drilling
  • Not reactive by default
  • Reactive with ref / reactive
  • Best for global/deep dependencies

You may also like...