1

I've been digging into React's codebase and I discovered that when you write class App extends React.Component, you are actually extending an object created by the following function:

function Component (props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = {};
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue ;
}

Component.prototype.isReactComponent = {};

Component.prototype.setState = function(partialState, callback) {
  this.updater.enqueueSetState(this, partialState, callback, 'setState')
}

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
}

What is the advantage of creating classes this way as opposed to just writing an ES6 class?

6
  • 3
    The advantage is that this code runs in environments that don't support class syntax without having to preprocess the code. It produces the same result as using class. Mar 19, 2019 at 20:21
  • Not sure why they aren't using Babel to transpile it down ... Mar 19, 2019 at 20:26
  • Maybe so that it supports being extended in ES5 style?
    – Bergi
    Mar 19, 2019 at 20:33
  • An ES6 class it's only syntactic sugar for the developer at the end a class will be converted to a function
    – OsDev
    Mar 19, 2019 at 20:59
  • @OsDev No, it won't be converted to different syntax. And classes are not only syntactic sugar.
    – Bergi
    Mar 19, 2019 at 21:06

1 Answer 1

1

https://caniuse.com/#search=es6%20class

This has to do with browser compatibility. Ensuring that the code can run where the class sytax is not supported without having to transpile with something like Babel.

3
  • This is a likely reason, but can you prove that it's the reason why React specifically is doing this?
    – Bergi
    Mar 19, 2019 at 21:07
  • It's probably already been transpiled with babel to ES5 from their dev environment. =)
    – Mark
    Mar 19, 2019 at 21:11
  • 1
    No, OP linked to the source code not to the transpiled code.
    – Bergi
    Mar 19, 2019 at 21:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.