Composition vs Inheritance in React

Composition vs Inheritance in React

·

3 min read


In React, the composition is the natural pattern of the component model. It's how we build component form other components, of varying complexity and specialization through props. Depending on how generalized these components are they can be used in building many other components.


React has powerful composition model, and I recommend using the composition instead of inheritance to reuse code between components. Here, we will consider a few problems where developers new to React often reach for inheritance, and how we can solve them with composition.

Containment

Some components don't know their children ahead of time. React recommends that such components use the special children prop to pass children elements directly into their output:

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

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

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

Specialization

Sometimes we think about components as being special cases of other components. For example, we might say that 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:

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

function WelcomeDialog() {
    return (
    <Dialog 
        title="Welcome"
        message="Thank you for visiting!" />
    ); 
}

So what about inheritance?

Facebook uses React thousands of components, and they haven't found any use cases where they would recommend creating component inheritance hierarchies.

Props and composition give you all the flexibility you need to customize a component's look and behaviour explicitly and safely. Remember that, a component may accept arbitrary props, including primitive values, React elements, or functions.


⚡Thanks For Reading | Happy Coding📘

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!