Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created February 6, 2024 12:47
Show Gist options
  • Save kingluddite/dab207363902b48b884eb5c652f4d14e to your computer and use it in GitHub Desktop.
Save kingluddite/dab207363902b48b884eb5c652f4d14e to your computer and use it in GitHub Desktop.
Problems with prop drilling in React

Problems with prop drilling in React

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment