What is the difference between using constructor vs getInitialState in React / React Native?
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.
1 2 3 4 5 6 | class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; } } |
Is equivalent to:
1 2 3 4 5 | var MyComponent = React.createClass({ getInitialState() { return { /* initial state */ }; }, }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.