Skip to main content
InterviewHubPRO
Section Overview
Q350

Question 350 of 407

Part 9: React Hooks Deep Dive (262 - 316)

86%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What is the difference between constructor and getInitialState?

junior LevelCode ExampleHooks
  • constructor: Used in ES6 class components (class MyComponent extends React.Component) to initialize local component state by assigning an object to this.state and to bind event handler methods.
  • getInitialState: Used in legacy React.createClass() components to return the initial state object.

In modern React functional components, both are superseded by the useState() Hook (const [state, setState] = useState(initialValue)).

jsx
// Modern Functional Component (Standard):
const [user, setUser] = useState({ name: 'Alex' });

// ES6 Class Component:
class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: 'Alex' };
  }
}