Search code examples
javascriptreactjsclassfactory-pattern

Why React choose not to adhere class pattern with ReactElement?


I am currently reading React source code. In most of the cases they prefer class pattern over factory function as constructor of instances.

Until I encounter ReactElement: react/packages/react/src/ReactElement.js

The comment shows that they choose NOT to adhere class pattern here on purpose.

/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, instanceof check
 * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @params omitted
 * ...
 */
const ReactElement = function(type, key, ref, self, source, owner, props) {
  // code omitted
}

But according to this comment, there are at least two obvious shortcomings,

  1. User can not use new ReactElement() to instantiate element (the way they used to elsewhere).
  2. element instanceof ReactElement no longer works.

I believe that they made that choice for a good reason, but just not listed in the comment. Anyone can give some explaination?


Solution

  • The function just returns a plain object with $$typeof: REACT_ELEMENT_TYPE. There's no need to make it a class constructor. I'd presume doing this is more optimizable by JS engines.

    User can not use new ReactElement() to instantiate element (the way they used to elsewhere).

    React end-users never call this by themselves. They call React.createElement().

    element instanceof ReactElement no longer works.

    As an end user (c.f. a React internals developer), have you ever needed something like that? You'd be inspecting the internals of an JSX tree.