Class components in React are the older way of writing components that can have their own state and lifecycle methods. Before the introduction of hooks in functional components, class components were the primary way to handle state and side effects.
Basic Class Component
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return Hello, {this.props.name}!
;
}
}
export default Greeting;
State in Class Components
Class components can have their own state, which is managed using the this.state property and updated using the this.setState method.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
You clicked {this.state.count} times
);
}
}
export default Counter;
Lifecycle Methods
Class components have several lifecycle methods that can be overridden to run code at specific points in the component’s lifecycle.
- componentDidMount: Called once, immediately after the component is mounted.
- componentDidUpdate: Called immediately after updating occurs.
- componentWillUnmount: Called just before the component is unmounted and destroyed.
Advantages and Disadvantages of Class Components
Advantages :
- State and Lifecycle Methods: Class components can manage state and have lifecycle methods.
- Inheritance: They provide a more traditional OOP approach, which might be familiar to developers coming from other OOP languages.
Disadvantages :
- Boilerplate: They tend to have more boilerplate code compared to functional components.
- Complexity: Managing
this
keyword can sometimes lead to bugs and confusion. - Performance: They may have a slight performance overhead compared to functional components with hooks.