Props drilling 📸 useContext()

Props drilling 📸 useContext()

Props Drilling

Passing data from a parent component down through multiple levels of nested child components via props is called props drilling. This can make the code hard to manage and understand as the application grows. It’s not a topic but a problem. How it’s a problem?

In react, Data flows from top to bottom component. Like this…

Parent -> Children -> Grand Children

Now I will show you two cases. Each case represents a different set of data flow.

Case 1 👇

Description: A hand-drawn illustration to help visualize props drilling:

Code

👉🏽 TopLevelComponent.jsx

// TopLevelComponent.jsx
import React from react;
import IntermediateComponent1 from ./IntermediateComponent1;

const TopLevelComponent = () => {
const user = { name: Jorjis Hasan, age: 22 };

return (
<div>
<h1>Top-Level Component</h1>
<IntermediateComponent1 user={user} />
</div>
);
};

export default TopLevelComponent;

// IntermediateComponent1.jsx
import React from react;
import IntermediateComponent2 from ./IntermediateComponent2;

const IntermediateComponent1 = ({ user }) => {
return (
<div>
<h2>Intermediate Component 1</h2>
<IntermediateComponent2 user={user} />
</div>
);
};

export default IntermediateComponent1;

// IntermediateComponent2.jsx
import IntermediateComponent3 from ./IntermediateComponent3;

const IntermediateComponent2 = ({ user }) => {
return (
<div>
<h3>Intermediate Component 2</h3>
<IntermediateComponent3 user={user} />
</div>
);
};

export default IntermediateComponent2;

// IntermediateComponent3.jsx
import EndComponent from ./EndComponent;

const IntermediateComponent3 = ({ user }) => {
return (
<div>
<h4>Intermediate Component 3</h4>
<EndComponent user={user} />
</div>
);
};

export default IntermediateComponent3;

// EndComponent.jsx
const EndComponent = ({ user }) => {
return (
<div>
<h5>End Component</h5>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
</div>
);
};

export default EndComponent;

See how we had to pass data down through layers. For the sake of EndComponents needs, we had to pass user data through 3 extra components(IntermediateComponent1, IntermediateComponent3, IntermediateComponent3). This is absolutely not clean code.

Case 2 🔽

Description: A hand-drawn illustration to help visualize Case 2 data flow.

Code:

Sorry! Sorry! Sorry!
I can’t code it up by just passing props. Even though I code, that would not make sense.

Well, let’s hand down the best practices. We have 2 consistent solutions that can be used against any complex data flow.

React built-in useContext Api
State Management Library

Please follow and like us:
Pin Share