Comments

React – Composition Vs. Inheritance

React Composition

source: https://en.wikipedia.org/wiki/React_(JavaScript_library)

As software developers we resort to to different architectural methodologies to solve our problems. Did you know that the React team recommends use of Composition over Inheritance?

Before we learn about why Composition is the preferred method in React, let’s learn the differences between Composition and Inheritance.

Inheritance

Those familiar with Object Oriented Programming are well aware of Inheritance and use it on a regular basis. When a child class derives properties from it’s parent class, we call it inheritance. There are variety of use-cases where inheritance can be useful.

Example: A car is a vehicle can be modeled with inheritance.

Let’s look at a simple example of inheritance in JavaScript showing a Car is a Vehicle.

class Vehicle {
 
  constructor (name, type) {
    this.name = name;
    this.type = type;
  }
 
  getName () {
    return this.name;
  }
 
  getType () {
    return this.type;
  }
}
class Car extends Vehicle {
 
  constructor (name) {
    super(name, 'car');
  }
 
  getName () {
    return 'The car's name is: ' + super.getName();
  }
}

You can notice here from the code above that, the Car extends/inherits its properties from the base class, Vehicle.

Composition

Composition is also a familiar concept in Object Oriented Programming. Instead of inheriting properties from a base class, it describes a class that can reference one or more objects of another class as instances.

Example: A car has an engine can be modeled with composition.

Now that we have recapped the differences between Inheritance and Composition, let’s dive into what’s the right fit for React.

React prefers Composition over Inheritance

Here is what Dan Abramov, React’s core team member has to say about it.

Both Inheritance and Composition, aim towards code reuse and cleaner code structure. But what does the React team recommend?

React recommends use of Composition over Inheritance, here is why. Everything in React is a component, and it follows a strong component based model. This is one of the primary reasons that composition is a better approach than inheritance for code reuse.

Take a look at the simple code snippet below to understand how composition works in React.

export default class Heading extends React.Component {
  render () {
    return (
       <div>
         <h1>{this.props.message}</h1>
       </div>
    )
  }
}
Heading.propTypes = {
  message: PropTypes.string
}
Heading.defaultProps = {
  message: 'Heading One'
}

The component Heading is used to display a text message. Notice that for the Heading component the message needs to be passed in as a prop. If we fail to pass a prop, it uses the default props. The idea is that we can reuse the Heading component all across our code, and pass it a different heading message, depending on the screen that invokes it.

The code snippet below shows how Heading can be used.

// Container Component Screen One
export default class ScreenOne extends React.Component {
  render () {
    return (
     <div>
     	  <Heading message={'Custom Heading for Screen One'}/>
      </div>
    )
  }
}

Notice here that ScreenOne is a container component. It uses the Heading component to display it’s heading. It passes a custom message as a prop to the Heading component as shown above.

Let’s add another container component to our code and call it ScreenTwo.

// Container Component Screen Two
export default class ScreenTwo extends React.Component {
  render () {
    return (
     <div>
     	  <Heading message={'Custom Heading for Screen Two'}/>
      </div>
    )
  }
}

Notice here that ScreenTwo uses the same Heading component, but it passes a different message as prop to the component.

What did we just demonstrate?

From the code above we demonstrated that a component can be called by another container component. And when calling a component, you can pass to it some props. We also learned that different container components can pass different props to the same component (Heading in our case).

The code above just demonstrated a simple use-case of React Composition.

In a blog post, written by Facebook they had mentioned that they had never used Inheritance in their React code across thousands of components. This shows how just using Composition can solve code reuse problems in React.

Higher Order Components – Another Approach to Composition

A Higher Order Component (HOC) is a function that takes a component and returns a component. One use case is to inject additional props or context. This is an advanced technique that is used in React.

We can dedicate another blog post, to explore High Order Components.

Common Components that use Composition

There are many common React Components and libraries that use Composition in React.

If you have used react-redux library, it follows the same approach in the connect method. The react-redux library is used to make the redux store available to the rest of the app. If you have not used Redux or worked with it, this would be a topic we can cover in another blog post.

This composition pattern is also seen in the react-styleable component.

Conclusion

In React using Composition and Props gives you all the flexibility that you would need. React does not say Composition is better than Inheritance. Composition just fits better within the React’s component structure.

If you are new to React and are considering reusing code, always go for React Composition over Inheritance. With the addition of the latest Hooks in React, re-using code is only going to be much easier.

Finally, if you are looking for great courses on React, I highly recommend Mosh’s course on Mastering React.

If you liked this post, please share and spread the word.

Adhithi Ravichandran is a Software Consultant based in Kansas City. She is currently working on building apps with React, React Native and GraphQL. She is a Conference Speaker, Pluralsight Author, Blogger and Software Consultant. She is passionate about teaching and thrives to contribute to the tech community with her courses, blog posts and speaking engagements.
Tags: , , ,

2 responses to “React – Composition Vs. Inheritance”

  1. […] React – Composition Vs. Inheritance – Programming with Mosh […]

  2. Matt says:

    So how come your Mastering React course uses inheritance rather than composition when creating the reusable form component?

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts