Quiz

Explain the composition pattern in React

Topics
React
在GitHub上编辑

TL;DR

The composition pattern in React is a way to build components by combining smaller, reusable components. Instead of using inheritance, React encourages composition to create complex UIs. You can pass components as children or props to other components to achieve this. For example:

function WelcomeDialog() {
return (
<Dialog>
<h1>Welcome</h1>
<p>Thank you for visiting our spacecraft!</p>
</Dialog>
);
}
function Dialog(props) {
return (
<div className="dialog">
{props.children}
</div>
);
}

Composition pattern in React

What is composition?

Composition is a design principle that involves combining smaller, reusable components to build more complex components. In React, this is preferred over inheritance for creating complex UIs.

How to use composition in React

Passing components as children

One common way to use composition is by passing components as children to other components. This allows you to nest components and create a hierarchy.

function Dialog(props) {
return (
<div className="dialog">
{props.children}
</div>
);
}
function WelcomeDialog() {
return (
<Dialog>
<h1>Welcome</h1>
<p>Thank you for visiting our spacecraft!</p>
</Dialog>
);
}

Passing components as props

Another way to achieve composition is by passing components as props. This allows for more flexibility and customization.

function SplitPane(props) {
return (
<div className="split-pane">
<div className="split-pane-left">
{props.left}
</div>
<div className="split-pane-right">
{props.right}
</div>
</div>
);
}
function App() {
return (
<SplitPane
left={<Contacts />}
right={<Chat />}
/>
);
}

Benefits of composition

  • Reusability: Smaller components can be reused across different parts of the application.
  • Maintainability: Easier to manage and update smaller components.
  • Flexibility: Components can be easily combined in different ways to create complex UIs.

When to use composition

  • When you need to create complex UIs from smaller, reusable components.
  • When you want to avoid the pitfalls of inheritance, such as tight coupling and difficulty in managing state.

Further reading

在GitHub上编辑