Should I Use Inheritance In React?
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>);
}