DEV Community

vishwa v
vishwa v

Posted on Edited on

react-5

What is Prop Drilling?
Definition: Passing data (props) from a parent component down through several intermediate components until it reaches the child that actually needs it.

Problem: Intermediate components receive props they don’t use, cluttering the code and making debugging harder.

function Parent() {
  const message = "Hello from Parent";
  return <Child message={message} />;
}

function Child({ message }) {
  return <Grandchild message={message} />;
}

function Grandchild({ message }) {
  return <p>{message}</p>;
}

Enter fullscreen mode Exit fullscreen mode

Solutions to Avoid Prop Drilling

React Context API

Provides a way to share values without passing props manually.

const UserContext = createContext();

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

function GrandChild() {
  const user = useContext(UserContext);
  return <p>Hello, {user}!</p>;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)