SmartCodingTips

πŸ”½ Props Drilling in React

Props drilling refers to the process of passing data from a parent component to a deeply nested child component through intermediate components, even if those intermediates don’t need the data.


πŸ“‰ What is Props Drilling?

When data is needed in a component deep in the tree, but must be passed through several intermediary components that don't use it β€” that's called props drilling.

// App β†’ Parent β†’ Child β†’ Target
function App() {
  return <Parent user="Sangram" />;
}

function Parent({ user }) {
  return <Child user={user} />;
}

function Child({ user }) {
  return <TargetComponent user={user} />;
}

function TargetComponent({ user }) {
  return <p>Hello, {user}</p>;
}

⚠️ Why is it a Problem?

  • Clutters intermediary components with unused props.
  • Makes refactoring and maintenance harder.
  • Increases coupling between components.

🧠 Solutions to Avoid Props Drilling

  • React Context API: Share data globally without manually passing props.
  • State Management Tools: Redux, Zustand, or Jotai for global state control.
  • Custom Hooks: Encapsulate logic and share across components.
// Using Context API
const UserContext = React.createContext();

function App() {
  return (
    <UserContext.Provider value="Sangram">
      <Parent />
    </UserContext.Provider>
  );
}

function TargetComponent() {
  const user = React.useContext(UserContext);
  return <p>Hello, {user}</p>;
}

πŸ“‹ Summary

  • Props drilling happens when data is passed through components unnecessarily.
  • It increases code complexity and reduces maintainability.
  • Use Context API or global state to avoid this pattern.