Ad

Decorators Or Subclassing Is Best Pattern For React.Component

Which is the recommended way and why?

way_1:(Using inheritance)

class BaseComponent extends React.Component {

    //Other functions

    log = (msg) => {
        console.log(`[${this.constructor.name}]`, msg);
    }

    //Other functions
}

export default BaseComponent;


class XyzComponent extends BaseComponent {

    //Other functions

    someFunction = () => {
        this.log("Some log");
    }

    //Other functions
}

export default XyzComponent;

way_2:(Using decorators)

function withLog(ComposedComponent) {
    return class withLog extends Component {
        log = (msg) => {
            console.log(`[${this.constructor.name}]`, msg);
        }
    }
};

export default withLog;

@withLog
class XyzComponent extends React.Component {

    //Other functions

    someFunction = () => {
        this.log("Some log");
    }

    //Other functions
}

I liked way_1 because it looks like other OOPs based languages. Which makes constancy and easier to understand. But everywhere else people saying about decorators. So I'm bit confused.

Ad

Answer

People likely reccomend decorators because they internalize the functionality you want.

When you inherit from BaseComponent in your first example you're creating a strong (inheritence) dependency between XyzComponent and BaseComponent. Then, any changes to BaseComponent may have an indirect effect on XyzComponents.

A more likely scenario is if--later down the line--you decide to change XyzComponent's logging method. If you took the first approach it might be difficult to "cut out the middle" and inherit from React.Component because other parts of your codebase might be accessing XyzComponent through its BaseComponent superclass. In that case, you'd have to ensure that your modifications don't violate BaseComponent's contract.

So, although the inheritence approach is easy to grasp and very OO it might cause headaches later. If you're aware of those headaches make a judgement call - I personally find inheritence to be self-explanatory wheras the decorators are a little more indirect.

(This answer can be summed up as: "Prefer composition over inheritence")

Ad
source: stackoverflow.com
Ad