JAVASCRIPT

Manage Shared State with Vue 3 Provide/Inject

Learn to efficiently share and manage state across deeply nested components in Vue 3 using the `provide` and `inject` API, effectively avoiding prop drilling.

// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <p>Shared Message: {{ sharedMessage }}</p>
    <button @click="changeMessage">Change Shared Message</button>
    <ChildComponent />
  </div>
</template>

<script setup>
import { ref, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';

const sharedMessage = ref('Hello from Parent!');

const changeMessage = () => {
  sharedMessage.value = 'Message updated by Parent!';
};

// Provide the message and a function to update it
provide('messageKey', sharedMessage);
provide('updateMessageKey', (newMessage) => {
  sharedMessage.value = newMessage;
});
</script>

// ChildComponent.vue
<template>
  <div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
    <h2>Child Component</h2>
    <p>Injected Message: {{ injectedMessage }}</p>
    <button @click="handleClick">Update from Child</button>
  </div>
</template>

<script setup>
import { inject } from 'vue';

// Inject the message and the update function
const injectedMessage = inject('messageKey');
const updateMessageFromChild = inject('updateMessageKey');

const handleClick = () => {
  updateMessageFromChild('Message updated by Child!');
};
</script>
How it works: This example showcases how `provide` and `inject` in Vue 3 enable communication between components without explicit prop drilling. The `ParentComponent` uses `provide` to make a reactive `ref` (`sharedMessage`) and an update function available to all its descendants. `ChildComponent` then uses `inject` to access these provided values. When the `sharedMessage` is updated in either component, the change automatically reflects in all injected instances, demonstrating a simple shared state pattern.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs