React Class Components
Understanding the traditional way of building stateful components in React.
Before Hooks were introduced in React 16.8, class components were the primary way to create components that needed to manage state or use lifecycle methods. While modern React development heavily favors function components with Hooks, understanding class components is still valuable for working with older codebases or certain advanced scenarios.
A class component is an ES6 class that extends `React.Component` and implements a `render()` method.
import React from 'react';
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// Usage: <Welcome name="Student" />Key Features:
- `render()` method: Required method that returns JSX to describe the UI.
- `this.props`: Access props passed to the component.
- `this.state`: Manage internal component data that can change over time. Initialized in the `constructor` and updated with `this.setState()`.
- Lifecycle Methods: Special methods that get called at different phases of a component's life (e.g., `componentDidMount`, `componentWillUnmount`, `shouldComponentUpdate`).
Test Your Knowledge
How do you define a class component in React?
Which method is required in a React class component?
How is `state` typically initialized in a class component?
How do you update the state in a class component?