Web / ReactJS Interview questions
What is the role of constructor() in React components?
Implement a constructor in your React component when,
- Initializing local state by assigning an object to this.state.
- Binding event handler methods to an instance.
The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.
constructor(props) { super(props); // Don't call this.setState() here! this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.
More Related questions...