Hasty Briefsbeta

Bilingual

How Does React Tell a Class from a Function? — overreacted

13 hours ago
  • React treats components differently based on whether they are functions or classes, needing to call functions directly or instantiate classes with `new` and call `render`.
  • The `new` operator in JavaScript creates an object for class constructors, but using it with arrow functions or non-class functions causes errors or unwanted behavior.
  • React cannot simply use `new` for all components because it breaks arrow functions and prevents support for primitive return types.
  • React distinguishes classes from functions by checking for a special `isReactComponent` flag on the prototype, which is added to `React.Component`.
  • Using `instanceof` to check class inheritance is unreliable due to issues like multiple React copies and missing static properties in some transpiled code.
  • The `isReactComponent` flag on `React.Component.prototype` provides a practical and reliable way for React to determine component type.