How To Avoid Prop Drilling in React Using Component Composition

No Redux or Context API

Olusola Samuel
Jul 29 · 5 min read
Image for post
Image for post

Why is Prop Drilling a Problem?

Image for post
Image for post

How to Solve the Problem

How to Avoid Prop Drilling Using Component Composition

function LoginForm(props){
return (
<Input name="fname" />
<Button onClick={props.handleClick} />)
}

What is the actual problem we are trying to solve?

The untamed powers of the children prop

<ReactComponent1>
<ReactComponent2 />
</ReactCompoent1>
function ReactComponent1({ children }) {
return
(<div> I render my children
{children}
</div>)
}
<ThirdComponent>
<h3>I am the third component</h3>
<ComponentNeedingProps content={content} />
</ThirdCompoent>
function ThirdComponent({ children }) {
return (
<div>
<h3>I am the third component</h3>
{children}
</div>
);
}
function App() {
const content = "Who needs me?";
return (
<div className="App">
<FirstComponent>
<SecondComponent>
<ThirdComponent>
<ComponentNeedingProps content={content} />
<ThirdComponent>
</SecondComponent>
</FirstComponent>
</div>
);
}
function FirstComponent({ children }) {
return (
<div>
<h3>I am the first component</h3>;
{ children }
</div>
);
}
function SecondComponent({ children }) {
return (
<div>
<h3>I am the second component</h3>;
{children}
</div>
);
}
function ThirdComponent({ children }) {
return (
<div>
<h3>I am the third component</h3>
{children}
</div>
);
}
function ComponentNeedingProps({ content }) {
return <h3>{content}</h3>
}

When should you use the Context API?

JavaScript In Plain English

New articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store