What are Composition and Inheritence?

  • Inheritence comes from a class's ancestors
  • Composition is data passed down to children as props

Composition vs Inheritance

  • Inheritance can be overused
  • Composition of behavior can be simpler and easier
  • React supports using composition over deep inheritance

Composition - Using props.children

  • Any Components within <FancyBorder> become props.children
  • The parent component can wrap children in a <div> for layout/style

Composing Behavior with Components

/* FancyBorder will compose with children*/
function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>

/* WelcomeDialog uses FancyBorder with children*/
function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!

Composition - Child Groups

  • Sometimes components have children in several places
  • Assigning the child components to prop names can help organize
function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
      <div className="SplitPane-right">

function App() {
  return (
        <Contacts />
        <Chat />
      } />

Composition - Classes Work Too

  • Both Stateless Functions and Classes compose
  • Specific Components can configure General Components
  • Props can be used to configure

Composition - When Inheritance?

  • Facebook doesn't use inheritance beyond initial Component Classes
  • Frontends can be built using a mixture of 'general' and 'specific' components
  • Use Props to pass specific attributes and children to render specific behavior
  • Behavior shared within Components such as logic or utilities can be shared as JavaScript libraries or modules
  • Using import is more useful and less restricting then extends