20 Feb 2024
Class components are a type of component in React.js that are defined using ES6 classes. They extend the base React.Component class and have their own state, lifecycle methods, and other features.
In class components, the state is typically managed using this.state and updated using this.setState(). Class components also have access to lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount, which allow developers to define behavior at specific points in the component's lifecycle. However, with the introduction of functional components and hooks, class components are becoming less common in modern React development.
Example of a React class component with all the major lifecycle methods:
import React, { Component } from 'react';
class LifecycleExample extends Component {
constructor(props) {
super(props);
this.state = {
message: 'Hello, World!',
};
console.log('1. Constructor');
}
static getDerivedStateFromProps(nextProps, nextState) {
console.log('2. getDerivedStateFromProps');
return null;
}
shouldComponentUpdate(nextProps, nextState) {
console.log('3. shouldComponentUpdate');
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('4. getSnapshotBeforeUpdate');
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('5. componentDidUpdate');
}
componentDidMount() {
console.log('6. componentDidMount');
}
componentWillUnmount() {
console.log('7. componentWillUnmount');
}
handleClick = () => {
this.setState({ message: 'Updated Message!' });
};
render() {
console.log('8. Render');
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.handleClick}>Update Message</button>
</div>
);
}
}
export default LifecycleExample;
Explanation of the lifecycle methods:
- Constructor: Called when the component is initialized.
- getDerivedStateFromProps: Used to update the state based on changes in props. Rarely used.
- shouldComponentUpdate: Determines if the component should re-render. Can be used for performance optimization.
- getSnapshotBeforeUpdate: Captures information before the DOM is updated. Rarely used.
- componentDidUpdate: Called after the component has been updated.
- componentDidMount: Called after the component has been mounted to the DOM.
- componentWillUnmount: Called before the component is removed from the DOM.
- Render: The main method that returns JSX to define the component's UI.
Note: Not all lifecycle methods are used in every component, and in many cases, you might only need a subset of these methods based on your specific requirements. Additionally, with the introduction of React Hooks, you can achieve similar functionality in functional components with the useEffect hook.