Class components were the primary way to define components in React before the introduction of Hooks in functional components. Although functional components are now preferred, class components are still used in many projects, especially older ones.
1. What Are Class Components?
A class component is a React component defined using an ES6 class. It extends the React.Component
base class and must include a render()
method, which returns the JSX representing the UI.
2. Syntax of Class Components
Basic Class Component
import React, { Component } from 'react'; class Welcome extends Component { render() { return <h1>Welcome to React!</h1>; } } export default Welcome;
3. Key Features of Class Components
- State Management: Class components have a built-in
state
object for managing local state. - Lifecycle Methods: Class components support lifecycle methods like
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
. - Props Handling: Class components receive
props
as an implicit property.
4. State in Class Components
The state
object allows you to manage component-specific data that can change over time.
Using State
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 ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } } export default Counter;
5. Lifecycle Methods in Class Components
Class components provide lifecycle methods to handle component initialization, updates, and unmounting.
Common Lifecycle Methods
componentDidMount()
: Invoked after the component is mounted to the DOM.componentDidUpdate(prevProps, prevState)
: Called after updates to props or state.componentWillUnmount()
: Called just before the component is removed from the DOM.
Example Using Lifecycle Methods
import React, { Component } from 'react'; class Timer extends Component { constructor(props) { super(props); this.state = { time: 0 }; } componentDidMount() { this.timerID = setInterval(() => { this.setState({ time: this.state.time + 1 }); }, 1000); } componentWillUnmount() { clearInterval(this.timerID); } render() { return <p>Time: {this.state.time} seconds</p>; } } export default Timer;
6. Props in Class Components
Props are passed to class components just like functional components. They can be accessed using this.props
.
Example Using Props
import React, { Component } from 'react'; class Greeting extends Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } // Usage <Greeting name="John" />;
7. Event Handling in Class Components
Class components handle events by defining methods and binding them to this
if necessary.
Example: Event Handling
import React, { Component } from 'react'; class ClickMe extends Component { handleClick() { alert('Button clicked!'); } render() { return <button onClick={this.handleClick}>Click Me</button>; } } export default ClickMe;
8. Comparison: Functional vs. Class Components
Feature | Class Components | Functional Components |
---|---|---|
Syntax | ES6 class | JavaScript function |
State Management | this.state |
useState Hook |
Lifecycle Methods | Explicit (componentDidMount , etc.) |
useEffect Hook |
Performance | Slightly slower due to lifecycle overhead | Faster with Hooks |
Code Complexity | More boilerplate | Minimal and modern syntax |
9. Best Practices for Class Components
- Use constructor only when you need to initialize state or bind methods.
- Avoid deep nesting of components to maintain readability.
- Use
setState
instead of directly modifying the state object. - Optimize performance with lifecycle methods like
shouldComponentUpdate
.
10. Example: Complete Class Component
import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; componentDidMount() { console.log('Component Mounted'); } componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { console.log(`Count updated: ${this.state.count}`); } } componentWillUnmount() { console.log('Component Unmounted'); } render() { return ( <div> <h1>React Class Component</h1> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } } export default App;
11. When to Use Class Components
- Legacy Projects: Many older React projects are built with class components.
- Working with Third-Party Libraries: Some libraries or tools may still rely on class components.
However, for new projects, it’s recommended to use functional components with Hooks due to their simplicity and modern capabilities.
Conclusion
Class components are an important part of React’s history, offering state and lifecycle features before Hooks were introduced. While functional components are now the standard, understanding class components helps developers work with legacy React codebases and deepen their knowledge of React’s evolution.