InterviewHubPRO
Section Overview
Q387

Question 387 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

87%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

What is the difference between constructor and getInitialState?

You should initialize state in the constructor when using ES6 classes, and getInitialState() method when using React.createClass().

markdown
**Using ES6 classes:**
javascript
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          /* initial state */
        };
      }
    }
ruby
**Using `React.createClass()`:**
javascript
    const MyComponent = React.createClass({
      getInitialState() {
        return {
          /* initial state */
        };
      },
    });
markdown
**Note:** `React.createClass()` is deprecated and removed in React v16. Use plain JavaScript classes instead.