Reasons to Avoid Nested Components
Introduction
During a project, I encountered an issue where unnecessary re-renders were occurring.
The problem was not just rendering, but the fact that the DOM was being completely redrawn with each render. The culprit was the use of nested components in the code.
In this article, I will explain why you should avoid using nested components.
Cheat Sheet
// Bad
const List = ({ hasWrapper, borderStyle, children }) => {
const Border = () => {
return <p style={borderStyle}>{children}</p>;
}
if (hasWrapper) {
return (
<Wrapper>
<Border />
</Wrapper>
);
}
return <Border/>;
};
// Good
const List = ({ hasWrapper, borderStyle, children }) => {
if (hasWrapper) {
return (
<Wrapper>
<Border borderStyle={borderStyle}>
{children}
</Border>
</Wrapper>
);
}
return (
<Border borderStyle={borderStyle}>
{children}
</Border>
);
};
const Border = ({ borderStyle, children }) => {
return <p style={borderStyle}>{children}</p>;
}
As shown above, you might use a nested component to reuse the code for Border and the props of List. However, in such cases, the children are unnecessarily repaint in the DOM with each render.