A simple example to illustrate why prop drilling can become tedious and cumbersome.
Imagine you have a React application with several nested components representing a user interface for a social media platform. Each component needs access to the user's information, such as username and profile picture, which is stored at the top-level component.
Here's how the component hierarchy might look:
<App>
<Navbar>
<UserMenu>
<UserProfile />
</UserMenu>
</Navbar>
<Feed>
<Post />
<Post />
{/* more nested components */}
</Feed>
</App>
In this scenario, if you want to pass the user's information (e.g., username and profile picture) down to the UserProfile
component, you'd need to pass them as props through each intermediate component:
// App.js
function App() {
const user = { username: 'exampleUser', profilePicture: 'example.jpg' };
return (
<div>
<Navbar user={user} />
<Feed user={user} />
</div>
);
}
// Navbar.js
function Navbar({ user }) {
return (
<div>
<UserMenu user={user} />
</div>
);
}
// UserMenu.js
function UserMenu({ user }) {
return (
<div>
<UserProfile user={user} />
</div>
);
}
// UserProfile.js
function UserProfile({ user }) {
return (
<div>
<img src={user.profilePicture} alt={user.username} />
<p>{user.username}</p>
</div>
);
}
As your application grows and you add more components, you'll find yourself passing the user
prop through more and more levels of nesting. This can make your codebase harder to maintain and understand, especially if you need to update the prop in multiple places.
Additionally, if you decide to refactor your component structure or rearrange your component hierarchy, you'll need to revisit every place where the user
prop is passed down and update the prop accordingly. This can be error-prone and time-consuming.
In summary, prop drilling can become tedious and cumbersome as your application grows in complexity, leading to decreased developer productivity and code maintainability.