Reputation: 2743
Say there are nested components, where data is passed from top to root, but only root component needs the data, how to deal with this more efficiently? Check the following example:
const Myform = () => {
return (
<Section title={'Nested component'} />
)
}
const Section = ({title}) => {
return (
<Card title={title} />
)
}
const Card = ({title}) => {
return (
<Title title={title} />
)
}
const Title = ({title}) => {
return (
<h2>{title}</h2>
)
}
Myform
passes title
data to Section
, then passes to Card
, then passes to root component Title
, where data is only needed in Title
component. The 2 middle components only pass data. I can see two problems:
Each middle component needs to accept title
, but has no use of title
at all;
If more middle components are needed, each of them needs to repeat the same process.
In fact only Myform
and Title
need to know the data. Is there a more efficient way to deal with this kind of scenario?
Upvotes: 3
Views: 150
Reputation: 5747
You can create the Title component at the top and pass that down instead of the props. This is what Facebook recommends here in their docs on Composition vs Inheritance
EG:
const Myform = () => {
return (
<Section Title={<Title title='Nested component' />} />
)
}
const Section = ({Title}) => {
return (
<Card Title={Title} />
)
}
const Card = ({Title}) => {
return (
<Title />
)
}
const Title = ({title}) => {
return (
<h2>{title}</h2>
)
}
In this example with so many levels it doesn't work that great - in that case the Context API might be better
Upvotes: 3