What is prop drilling?
Prop drilling is a term used in component-driven frontend development where a parent component sends props through child components that have no use for the props except to pass them down to be used by a deeply nested component.
Example
You’re building a Vue web application where the buttons have a blue background and white colored text. There’s one exception though. The button has a red background when used anywhere inside a modal.
To know when to change the color to red, the Button takes a prop, inModal
; a boolean value.
// ButtonComponent.vue
export default {
// ...
props: [ "inModal" ]
}
To pass the prop to the button in the Modal, we need to pass the prop to the Card component first. Which then passes the prop to the Button.
Now, for a two-step drill like this, there’s no pain in drilling the prop. Imagine the Card component was nested in other components inside the Modal component; CardListComponent
→ CartContentComponent
→ CartComponent
, etc. Then passing the inModal props through each of these in-between components would be a pain.
To battle the need to pass the props through components that have no use for them, Vue provides the Provide / Inject feature. It involves a parent component exposing labeled values, and making them accessible to every child, grandchild, or even great-grandchild component.
Here’s how you can use the Provide / Inject feature to eliminate prop drilling in our example.
// ModalComponent.vue
export default {
// ...
provide: { inModal: true }
}
// ButtonComponent.vue
export default {
// ...
inject: [ "inModal" ]
}
So the ModalComponent says, assign the value true to the label inModal and make it available to all descendants. The ButtonComponent says, inject whatever value my ancestors labeled inModal.
If no ancestor of Button provides a value with the label inModal, you’ll see a warning in your console.
[Vue warn]: injection "inModal" not found.
[Optional] Alternate Provide Syntax
When provide is set to an object, you can provide only static values to the nested components. However, you write provide as a method that returns an object when you need to make a reactive value available. In the method, you can access the this keyword; assuming you’re using the options API.
Provide / Inject can help you avoid prop drilling and write cleaner component compositions as a result. You can check the official docs for more information or clarification if you need any.