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 tothis.stateand to bind event handler methods.getInitialState: Used in legacyReact.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' };
}
}