Tech AI Insights

Vue.js Prop Drilling Explained: How to Avoid and Fix It

What is Prop Drilling?

Prop drilling is a way of passing data from a parent component to a child component. Normally, it’s not a bad practice if there are only one or two child components.

But imagine a situation where there is a tree of multiple child components under one parent, and only the last component in that tree needs the data. In this case, the data must be passed through every child component in the tree before reaching the last one.

This makes the code more complex and harder to maintain.

 

Props Drilling

 

The <Header> and <Navbar> components do not need all the props passed from the <App> component to <Menus>. They simply act as a bridge to pass the props from the parent component to the final <Menus> component. If more parent components are added in between, all of them will be affected. This is called prop drilling.

How to Stop Prop Drilling in Your Code?

In Vue.js, to prevent prop drilling, we can use provide and inject. The parent component acts as a dependency provider for all its child components. No matter how deep or far a child component is, it can easily access or inject the dependency provided by the parent.

 

Provide/Inject

Provide

To share data with child components, use the provide() function.

The provide function accepts two arguments.

The first argument is called the injection key, which can be a string or a symbol. Child components use this key to access the provided value. A single component can call the provide function multiple times with different keys.

The second argument is the provided value, which can be of any type, including reactive state like ref or reactive.

Inject

To get data from a parent or ancestor component, use the inject() function.

If the provided value is a ref, it stays the same when injected and is not automatically unwrapped. This keeps the reactive connection between the child and parent components.

Scroll to Top