function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
Composition means building components by nesting them and passing them to each other, instead of extending them. React prefers composition over inheritance.
Anything between a component's opening and closing tags is passed as the children prop. So a generic Card or Modal can render children inside its layout without knowing what they are. You can also pass JSX through other named props as slots, like header and footer.
Composition also reduces prop drilling. Imagine Layout only passes user through to a deeply nested Avatar. Instead, the parent can render <Layout><Avatar user={user} /></Layout>. Now Layout never needs to know about user.
There is a performance bonus too. children created by the parent do not re-render just because the wrapper's own state changed.
- React prefers composition over inheritance.
- The
childrenprop receives the nested JSX. - Named props can act as slots, like
headerandfooter. - Passing JSX down avoids prop drilling.
- When the wrapper's state changes,
childrencreated by the parent do not re-render.