Back
VueMediumNew
What is `provide`/`inject` and when should you use it over props?
Dependency injection across deeply nested components
Ideal Answer
provide/inject let an ancestor component pass data to any descendant, no matter how deeply nested, without having to pass props through every intermediate level (avoiding 'prop drilling').
JavaScript
// Ancestor
import { provide, ref } from 'vue'
const theme = ref('dark')
provide('theme', theme)
// Descendant, any depth
import { inject } from 'vue'
const theme = inject('theme')
Use it for cross-cutting concerns like themes, locale, or configuration shared across many components. For simple parent-child communication, props and emits are usually clearer since they're explicit; provide/inject can make data flow harder to trace if overused. Pinia is often preferred for global app state.