What is Class Component in React: Explanation and Example
class component in React is a way to create components using ES6 classes that extend React.Component. It allows you to use state and lifecycle methods to control the component's behavior and rendering.How It Works
A class component in React works like a blueprint for creating parts of your user interface. Imagine it as a recipe that tells React how to build and update a piece of the screen. It uses a JavaScript class that extends from React.Component, which gives it special powers like managing its own data (called state) and reacting to changes in that data.
When you create a class component, you define a render() method that returns what the UI should look like. React calls this method to know what to show on the screen. The component can also have special methods called lifecycle methods that run at different times, like when the component appears or disappears, helping you control side effects like fetching data or cleaning up.
Example
This example shows a simple class component that displays a greeting and a button to change the greeting when clicked.
import React from 'react'; class Greeting extends React.Component { constructor(props) { super(props); this.state = { message: 'Hello, friend!' }; } changeMessage = () => { this.setState({ message: 'Hi there!' }); }; render() { return ( <div> <h1>{this.state.message}</h1> <button onClick={this.changeMessage}>Change Greeting</button> </div> ); } } export default Greeting;
When to Use
Class components are useful when you need to manage complex state or use lifecycle methods in React. They were the main way to create components with state before React introduced hooks. You might still see them in older codebases or when working with libraries that expect class components.
For example, if you want to fetch data when a component loads or clean up resources when it unloads, class components let you do this with lifecycle methods like componentDidMount and componentWillUnmount. However, for new projects, functional components with hooks are recommended because they are simpler and more flexible.
Key Points
- Class components use ES6 classes and extend
React.Component. - They have a
render()method that returns JSX to display UI. - State is managed with
this.stateand updated withthis.setState(). - Lifecycle methods control behavior during mounting, updating, and unmounting.
- Functional components with hooks are now preferred for new React code.