Performance: Component composition
Component composition affects rendering speed and responsiveness by how components are structured and reused in React apps.
const MemoizedChild = React.memo(function Child() { return <div>Static content</div>; }); function Parent() { return <div>{Array(100).fill(null).map(() => <MemoizedChild />)}</div>; }
function Parent() { return <div>{Array(100).fill(null).map(() => <Child />)}</div>; } function Child() { return <div>{Math.random()}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unmemoized nested components with changing props | High (many re-renders) | High (many layout recalculations) | High (many paints) | [X] Bad |
| Memoized components with stable props | Low (minimal re-renders) | Low (few layout recalculations) | Low (few paints) | [OK] Good |
function Wrapper({ children }) {
return <div className="wrapper">{children}</div>;
}
function App() {
return (
<Wrapper>
<p>Hello</p>
<p>World</p>
</Wrapper>
);
}function Container(props) {
return <div>{props.children}</div>;
}
function App() {
return (
<Container>
<h1>Title</h1>
<h2>Subtitle</h2>
</Container>
);
}
// Usage
ReactDOM.render(<App />, document.getElementById('root'));Card component that accepts a header and footer as props and displays children content in the middle. Which is the best way to compose this component?Pass the test and this pattern moves unknown