ReactJS – Is Composition Better Than Inheritance In React?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (Is Composition Better Than Inheritance In React?).

In this article, we will learn about React topic ” Why Composition is better than Inheritance “. We will try to understand which works better in react, Inheritance or Composition using below points:

  • What are Composition and Inheritance ?
  • Composition vs Inheritance
  • Composition – Using props.children
  • Composition – Child Groups
  • Composition – Classes Work Too
  • What about Inheritance ?

Inheritance and Composition are two important parts of object-oriented programming when it comes to code reusability. Both of these concepts are also relevant to React components. Hence, the concept of inheritance vs composition is very important.

A famous quote about learning is :

He who learns but does not think, is lost! He who thinks but does not learn is in great danger.

So Let’s begin.


What are Composition and Inheritance ?

Composition and inheritance are the approaches to use multiple components together in ReactJS. This helps in code reuse. React recommends using composition instead of inheritance as much as possible and inheritance should be used in very specific cases only.

Inheritance uses the is-a relationship method. Derived components had to inherit the properties of the base component and it was quite complicated while modifying the behavior of any component. The composition aims for something better. Instead of inheriting the properties of other components, why not inherit only behavior, and add behavior to the desired component?

Composition does not inherit properties, only the behavior. This is a plus point but why? In inheritance, it was difficult to add new behavior because the derived component was inheriting all the properties of parent class and it was quite difficult to add new behavior. We had to add more uses cases. But in composition, we only inherit behavior and adding new behavior is fairly simple and easy.

For example, Let’s say we have a component to input username. We will have two more components to create and update the username field. We extended the UserNameForm component and extracted its method in child component using super.render().

Inheritance

class UserNameForm extends React.Component {
   render() {
      return (
         <div>
            <input type="text" />
         </div>
      );
   }
}
class CreateUserName extends UserNameForm {
   render() {
      const parent = super.render();
      return (
         <div>
            {parent}
            <button>Create</button>
         </div>
      )
   }
}
class UpdateUserName extends UserNameForm {
   render() {
      const parent = super.render();
      return (
         <div>
            {parent}
            <button>Update</button>
         </div>
      )
   }
}
ReactDOM.render(
   (<div>
      < CreateUserName />
      < UpdateUserName />
   </div>), document.getElementById('root')
);

Composition

class UserNameForm extends React.Component {
   render() {
      return (
         <div>
            <input type="text" />
         </div>
      );
   }
}
class CreateUserName extends React.Component {
   render() {
      return (
         <div>
            < UserNameForm />
            <button>Create</button>
         </div>
      )
   }
}
class UpdateUserName extends React.Component {
   render() {
      return (
         <div>
            < UserNameForm />
            <button>Update</button>
         </div>
      )
   }
}
ReactDOM.render(
   (<div>
      <CreateUserName />
      <UpdateUserName />
   </div>), document.getElementById('root')
);

Use of composition is simpler than inheritance and easy to maintain the complexity.


Composition vs Inheritance

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. We can differentiate the below points between Inheritance and Composition :

  • Inheritance can be overused.
  • Composition of behavior can be simpler and easier.
  • React supports using composition over deep inheritance.
  • Inheritance inherits the properties of other components while Composition does not inherit properties, only the behavior.
  • In inheritance, it was difficult to add new behavior because the derived component was inheriting all the properties of parent class and it was quite difficult to add new behavior. We had to add more uses cases. But in composition, we only inherit behavior and adding new behavior is fairly simple and easy.


Composition – Using props.children

Some components don’t know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic “boxes”.

We recommend that such components use the special children prop to pass children elements directly into their output. This lets other components pass arbitrary children to them by nesting the JSX.

Anything inside the <FancyBorder> JSX tag gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.

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

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

We can conclude that

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


Composition – Child Groups

While this is less common, sometimes you might need multiple “holes” in a component. In such cases you may come up with your own convention instead of using children.

React elements like <Contacts /> and <Chat /> are just objects, so you can pass them as props like any other data. This approach may remind you of “slots” in other libraries but there are no limitations on what you can pass as props in React.

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

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

We can conclude that

  • Sometimes components have children in several places
  • Assigning the child components to prop names can help organize


Composition – Classes Work Too

Sometimes we think about components as being “special cases” of other components. For example, we might say that a WelcomeDialog is a special case of Dialog.

In React, this is also achieved by composition, where a more “specific” component renders a more “generic” one and configures it with props.

Composition works equally well for components defined as classes.

function Dialog(props) {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        {props.title}
      </h1>
      <p className="Dialog-message">
        {props.message}
      </p>
      {props.children}
    </FancyBorder>
  );
}

class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSignUp = this.handleSignUp.bind(this);
    this.state = {login: ''};
  }

  handleChange(e) {
    this.setState({login: e.target.value});
  }

  handleSignUp() {
    alert(`Welcome aboard, ${this.state.login}!`);
  }

  render() {
    return (
      <Dialog title="Mars Exploration Program"
              message="How should we refer to you?">
        <input value={this.state.login}
               onChange={this.handleChange} />

        <button onClick={this.handleSignUp}>
          Sign Me Up!
        </button>
      </Dialog>
    );
  }
}

We can conclude that

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


What about 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

That’s all about in this article.



Conclusion

In this article, We understood which works better in react, Inheritance or Composition. Inheritance and composition both can be used for code reusability and for enhancing components but according to the core React team, we should prefer composition over inheritance.

Thanks for reading ! I hope you enjoyed and learned about Composition concept is better than Inheritance in React. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow the official website and tutorials of React below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version