React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What will happen if you use setState() in constructor?
When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize variables inside constructor.
Code Example
tsx
import React, { Component } from 'react';
class UserProfile extends Component {
constructor(props: any) {
super(props);
// ❌ WRONG: Triggers warning "Can only update a mounted or mounting component"
// this.setState({ username: 'Alex' });
// ✅ CORRECT: Directly assign the initial state object in constructor
this.state = {
username: 'Alex Morgan',
role: 'Frontend Architect',
};
}
render() {
return <div>User: {(this.state as any).username}</div>;
}
}