class declarations for components - why?


(Ido Ofir) #1

Class declarations seem to be the preferred way of creating components in React for some time now. as React.createClass() is going to be deprecated, I am trying to understand if there is an actual useful benefit that people see in class declarations in React ( and javascript in general ).

Personally I feel that class declarations do not belong in javascript and that favouring class declaration for React components to the point of deprecating React.createClass() may be a bit over the top.

I realise that people may feel a tendency towards a certain style of coding and opinions may vary and that’s ok, but from a pure practical point of view:

  • class declarations in javascript introduce new syntax rules and complexity to the language, while providing only an abstraction over the underlying prototype inheritance. official docs literally describe it as “syntactical sugar” and it seems that it’s main purpose is to make javascript feel like it has a more conventional inheritance model. more complexity is not a good thing if it does not provide a practical, useful advantage.
  • defining components in react using class declarations is longer, more complicated and less clear compared to React.createClass(). and you need to bind all of your custom functions to the instance manually…

While class declarations do provide a cleaner way of creating inheritance chains, this does not seem to have a lot of meaningful use in React. if you extend a component class other than React.Component you would be overriding the parent’s render function. a super class may be used as a bank of functions which do not need to be explicitly bound by an inheriting child, which is pretty much what a mixin used to do:

class A extends React.Component {

    constructor(props){
        super(props);
        this.log = this.log.bind(this);  // without this line it will log `null`.
    }

    log(){
        console.log(this);
    }

    render(){  // never really used by B
        return (
            <button onClick={ this.log }> Log A </button>
        )
    }
}

class B extends A {

    constructor(props){
        super(props);
    }

    render(){
        
        return (
            <button onClick={ this.log }> Log B </button>
        );
    }
}

It’s not that I see anything wrong with the code above, I am only trying to understand if there is a practical reason to prefer this pattern over what it is replacing. writing the same components using React.createClass would be almost half the code, which would make it clearer, so why is this pattern preferred? why do we need a longer way to say the same thing?