In React, class components are JavaScript classes that extend the React.Component
base class and contain a render()
method, which returns a JSX element representing the component’s rendered output. Class components can also have state and lifecycle methods, which allow them to manage data and perform actions at specific points in the component’s lifecycle.
Functional components, on the other hand, are simple JavaScript functions that accept props as an argument and return a JSX element representing the component’s rendered output. They do not have state or lifecycle methods, and are typically used for presentational components that do not need to manage any internal data or perform actions at specific points in their lifecycle.
You should use class components when you need to manage state or perform actions at specific points in the component’s lifecycle. You should use functional components when you don’t need to manage state or perform actions at specific points in the component’s lifecycle, and you just want to render some UI based on props.
With the introduction of React hooks in version 16.8, it is now possible to use state and other React features in functional components as well. This means that you may not always need to use class components, and you can use functional components even if you need to manage state or perform actions at specific points in the component’s lifecycle.
Here is an example of a class component in React:
import React, { Component } from 'react';
class MyClassComponent extends Component {
state = {
count: 0
};
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<button onClick={this.incrementCount}>Increment count</button>
<p>Count: {this.state.count}</p>
</div>
);
}
}
This class component has a state object that stores a count, and a method called incrementCount that increments the count by one. It also has a render method that returns a JSX element containing a button and a paragraph element displaying the current count.
Here is an equivalent functional component using React hooks
import { useState } from 'react';
function MyFunctionalComponent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment count</button>
<p>Count: {count}</p>
</div>
);
}
This functional component uses the useState
hook to add state to the component. It has a variable called count that stores the current count, and a function called setCount
that updates the count. It also has a JSX element that is similar to the one in the class component example.
I hope these examples help to illustrate the difference between class and functional components in React! Let me know if you have any other questions.
Top comments (0)