All Articles

Should I Use Inheritance In React?

Jack Herrington
Jack Herrington
August 20th, 2023

Question: Should I use inheritance in React?

Answer: No. Inheritance is a mechanism that was used in lots of different UI toolkits in the past, e.g. Swing, MFC, GWT, etc. But it is an anti-pattern in React.

Let's take a step back though, what is inheritance in React. Here is an example:


class Button extends React.Component {
render() {
return (<button>...</button>);
}
}
class IconButton extends Button {
render() {
return (<button><i>...</i>...</button>);
}
}

In this case we have declared a Button component, as a class, and then derived the IconButton from that original Button component.

The preferred method is to use composition, instead. If we continue with class components it would look something like this:


class Button extends React.Component {
render() {
return (<button>...</button>);
}
}
class Icon extends React.Component {
render() {
return (<i {...this.props}>...</i>);
}
}
class IconButton extends React.Component {
render() {
return (<Button><Icon /></Button>);
}
}

The IconButton component is composed of the Button and Icon components. And composition is preferred over inheritance in React.

Of course, in my opnion, you should not be using class components in React. They aren't officially deprecated but the updated React.dev documentation has no class components in it.

In functional components composition looks like this:


function Button() {
return (<button>...</button>);
}
function Icon() {
return (<i>...</i>);
}
function IconButton() {
return (<Button><Icon /></Button>);
}

Share this article with your friends

Subscribe for Free Tips, Tutorials, and Special Discounts

We're in this together!

We respect your privacy. Unsubscribe at any time.

Jack Herrington

Written by Jack Herrington

Jack Herrington is a Full Stack Principal Engineer who orchestrated the rollout of React/NextJS at Walmart Labs and Nike. He is also the "Blue Collar Coder" on YouTube where he posts weekly videos on advanced use of React and NextJS as well as other frontend technologies trends. His YouTube channel hosts an entire free courses on React and TypeScript. He has written seven books including most recently No-BS TypeScript which is a companion book to the YouTube course.