Beginner LevelVue JS
How do provide and inject share data across deep component hierarchies without prop drilling?
❓ Interview Prompt: Explain provide() and inject(), sharing global theme/auth state, and avoiding prop drilling across nested component trees.
When passing data from a root component to a deeply nested child component, passing props through 5 intermediate components (Prop Drilling) becomes cumbersome and fragile.
Dependency Injection ('provide' / 'inject'):
•
Ancestor Component: Calls 'provide("key", value)' to expose data or reactive refs to its entire subtree.
•
Descendant Component: Calls 'const val = inject("key")' to consume the provided value directly, regardless of how deep it sits in the component tree!
Code Implementation Example
javascript
// App.vue (Ancestor Root Component)
import { ref, provide } from 'vue';
const theme = ref('dark');
const toggleTheme = () => theme.value = theme.value === 'dark' ? 'light' : 'dark';
// Provide theme state and toggle function to entire component tree!
provide('themeContext', { theme, toggleTheme });
// DeepChildNode.vue (Nested Descendant Component)
import { inject } from 'vue';
// Inject provided context directly without prop drilling!
const { theme, toggleTheme } = inject('themeContext');💡Sharing reactive theme state across component trees using provide and inject.
🎯 Interview Key Takeaway
Use provide() in ancestor components and inject() in descendants to share state across deep component trees without prop drilling.
#provide#inject#Dependency Injection#Beginner
Back to all Vue JS Questions→