Vue 18: Provide / Inject
easy⏱ 5 mincoursevue
provide() up top, inject() down below
provide and inject are matched by key — a string or, in real apps, a Symbol (safer, avoids naming collisions between unrelated libraries/features). If you provide a reactive object (built with reactive(), or containing refs), any mutation from the injecting side flows back up naturally — the same underlying object is shared, not copied.
import { provide, inject, reactive } from 'vue';
// Ancestor:
const user = reactive({ name: 'Ada' });
provide('user', user);
// ANY descendant, any depth:
const injectedUser = inject('user');
console.log(injectedUser.name); // 'Ada', fully reactive
Keys, defaults, and reactivity
inject('key', defaultValue) accepts a second argument used when nothing was provided — handy for components meant to work standalone too. Remember: injecting a plain non-reactive value gives you a frozen snapshot; to keep the connection live (as in this lesson, where the child can toggle the theme), the provided value itself must be reactive.
Toggle the theme from 3 levels deep
Click the Toggle button inside DeepChild and watch the card's colors flip — that mutation happened on the SAME reactive object the root App provided, with MiddleLayer never even aware theme exists.