JAVASCRIPT
Prop Drilling Avoidance with Vue 3 Provide/Inject
Discover how to use Vue 3's Provide/Inject API to pass data down the component tree without prop drilling, ideal for themes, settings, or global configuration.
// ParentComponent.vue
<script setup>
import { provide, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const theme = ref('dark'); // Or 'light', etc.
provide('appTheme', theme); // Key 'appTheme', value `theme` ref
</script>
<template>
<div :class="theme">
<h1>Parent Component</h1>
<ChildComponent />
</div>
</template>
// ChildComponent.vue (or any descendant)
<script setup>
import { inject } from 'vue';
const appTheme = inject('appTheme'); // Injects the 'appTheme' ref
</script>
<template>
<p>Current Theme (from injected): {{ appTheme }}</p>
<GrandchildComponent />
</template>
// GrandchildComponent.vue (further descendant)
<script setup>
import { inject } from 'vue';
// Inject with a default value if not provided
const appTheme = inject('appTheme', 'default-light');
</script>
<template>
<p>Grandchild Component: Theme is {{ appTheme }}</p>
</template>
How it works: The `provide`/`inject` API in Vue 3 allows a parent component to provide data that any of its descendants (no matter how deep) can inject. This avoids "prop drilling" where props are passed through many intermediate components unnecessarily. In this example, `ParentComponent` provides an `appTheme` ref, which `ChildComponent` and `GrandchildComponent` then inject to access the current theme state. A default value can also be specified for `inject`, offering flexibility.