I mostly see JavaScript use classes as a constructor as following:
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter get area() { return this.calcArea(); } // Method calcArea() { return this.height * this.width; } }
What’s the reason React uses classes without using the contructor()
function, such as following? I don’t see classes being used to create instances.
class App extends Component { render() { return ( <div className="app-content"> </div> ) } }
Advertisement
Answer
What’s the reason React uses classes without using the
contructor()
function
From the JavaScript
class doc:
If you do not specify a constructor method, a default constructor is used.
So a constructor
exists for every class
whether a constructor method is specified or not.
I don’t see classes being used to create instances.
React
components implemented as classes get instantiated by React
as part of the rendering process.
Specifically, in the new React Fiber
creating an instance of a React
class component happens on this line of the source code.
But yes, @vicondin is right that the simple component from the question can be implemented as a function component, that class components used to be the only way to maintain state, implement lifecycle methods, etc., and that the new Hooks makes it possible to…
use state and other React features without writing a class.