Inheritance - is it "bad", or just "ugly"?


(Sigmoid) #1

So I think I found a case for component inheritance. All alternatives would result in less maintainable code as far as I can tell.

So I’d like to know if inheritance somehow breaks React, makes it less performant, or is not using it just a purely philosophical choice?


Here’s my use case: I’m using Material Components for the Web. This toolkit uses “foundation classes” for animations that need an adapter class with functions for DOM manipulation such as adding css vars or classes.

Adding and updating css vars without rerender is crucial to fluid animation. So this is only possible with a Ref - to the top level dom element of the material component.

Now a lot of the functionality between these component adapters is identical.

Also, I need a simple logic to translate semanitc props (such as “disabled”) to both css classes depending on the component (since MDC-Web follows BEM, so a disabled button is not “button disabled”, rather “button button–disabled”), and getter functions for the foundation class (eg. “isDisabled()”).

Also, almost all foundation classes expect adapter methods for adding and removing classes, so the react component needs to keep track of declarative classes, classes imperatively added, and classes imperatively removed.

Now, packaging all of this up in an “abstract” class without a render method, and extending it for each specific use case seems the best approach. I was thinking about HOCs, but from what I gather they can’t handle Refs properly.


(Mikayel) #2

Composition it the right way for react https://reactjs.org/docs/composition-vs-inheritance.html


(Emanuel Jöbstl) #3

I agree that this is a valid use case. You use inheritance to share logic, react also does that by always extending the base class React.Component.

As far as I understand react, the anti pattern would be UI composing with inheritance. Composition is definitely more elegant in this case.

Aside from that, inheritance will not break anything. It’s merely not the convenient react way of things, which will make your code harder to read and maintain for a react developer.