I've seen both used interchangeably.
What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?
In React, constructors are mainly used for two purposes: It used for initializing the local state of the component by assigning an object to this. state. It used for binding event handler methods that occur in your component.
getInitialState is the ES5 friendly method to define the initial state of a React component. JavaScript React. One fairly popular question that got asked on programming bulletin boards has to do with the similarities and differences between React's constructor and the built in method getInitialState .
You can use the constructor method or componentDidMount depending on what you need to be done. constructor will be called pre-render and componentDidMount post-render. The componentWillMount method is called right before a component mounts or the render method is called.
In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.
The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState
method when using React.createClass
.
See the official React doc on the subject of ES6 classes.
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; } }
is equivalent to
var MyComponent = React.createClass({ getInitialState() { return { /* initial state */ }; }, });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With