Method 2:
function BigComponent(props) {
const smallComponent1 = <div>{props.a}</div>;
const smallComponent2 = <div>{props.b}</div>;
return (
<div>
{smallComponent1}
{smallComponent2}
</div>
)
}
- If you want to a large UI into seperate smaller UI, this method will give you best performance because
- It is still just one big UI component.
- react just have to solve variable references.
- while re-rendering, BigComponent,smallComponent1 and smallComponent2 are rendered together as single unit.
- smallComponent1 and smallComponent2 cannot have their own state, life cycles and hooks.
- smallComponent1 and 2 needs to be re-initialized everytime Bigcomponent state is changed. So it is good practise to wrap them with
useMemo()if the result of those smallComponents are coming from an expensive computation.
Method 3:
function SmallComponent1({ a }) {
return <div>{a}</div>;
}
function SmallComponent2({ b }) {
return <div>{b}</div>;
}
function BigComponent(props) {
return (
<div>
<SmallComponent1 a={props.a} />
<SmallComponent2 b={props.b} />
</div>
)
}
-
React needs to resolve reference as well as execute the function after resolving the reference.
-
It is a composition of react’s actual child components into a large Component.
-
Child components are allowed to have their own
hooks. -
Child components are not re-initialized but are re-rendered if BigComponent state is changed.
-
There is chance of SmallComponent1 and SmallComponent2 getting re-rendered multiple times on BigComponents rendering once if small components are updating thier own state based on props change in parents.
-
if each SmallComponents are supposed to use multiple props which state of BigComponents, Keeping SmallComponents outside BigComponent does offer good developer experience.
-
I hope Method 1 and Method 4 can also be understood using these above points.
-
Note: childcomponents stored in variable and childcompoents as function becomes tricker if your application logic is using ref or DOM element for maininting focus or anchor point of rendering.