Skip to main content

Class Components (Live Playground)

Class components are another way to create components in React. They offer more features than functional components, such as state management and lifecycle methods. In this tutorial, we'll learn how to create class components and explore their benefits.

What is a Class Component?

A class component is a JavaScript class that extends React.Component. It must have a render method that returns a React element. Class components can manage their state and use lifecycle methods to perform side effects or update the DOM.

JavaScript
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

Benefits of Class Components

Before the introduction of React Hooks, class components were the only way to manage state and use lifecycle methods in a component. They offer several benefits:

  1. State management: Class components can manage their internal state using the this.state object and the setState method.
  2. Lifecycle methods: Class components can use lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount, to perform side effects or update the DOM.
  3. React context: Before React Hooks, class components were required to use the React context API to share data between components without passing props.

Creating a Class Component

To create a class component, you need to define a JavaScript class that extends React.Component and includes a render method that returns a React element. Here's an example:

JavaScript
import React from 'react';

class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

export default Greeting;

In this example, we created a simple Greeting component that takes a name prop and renders an h1 element.

To use the Greeting component, you can import it into another component and render it like this:

JavaScript
import React from 'react';
import Greeting from './Greeting';

class App extends React.Component {
render() {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
}
}

export default App;

In the App component, we imported the Greeting component and rendered it twice with different name props.

Live Playground, Try it Yourself

Conclusion

Class components are a powerful way to create components in React, offering features such as state management and lifecycle methods. Although React Hooks have made functional components more versatile, class components are still useful and important to understand, especially when working with older React codebases or projects that haven't adopted Hooks yet.