Middle
What are the lifecycle methods of a React class component?
sobes.tech AI
Answer from AI
Main lifecycle methods of a React class component:
constructor(props)— initializes state and binds methods.componentDidMount()— called after the component is mounted, suitable for data loading.shouldComponentUpdate(nextProps, nextState)— allows optimizing re-rendering by returning true/false.componentDidUpdate(prevProps, prevState)— called after the component updates.componentWillUnmount()— cleans up resources before the component is removed.
Example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component mounted');
}
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
componentDidUpdate(prevProps, prevState) {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will be unmounted');
}
render() {
return <div>{this.state.count}</div>;
}
}