In React, there are two main types of components: class components and functional components. Both types of components are used to define the UI of a React application, but they have some key differences that you should be aware of.
Class components are defined using a class that extends the React.Component base class. They have state, which is an object that stores data that can be used to render the UI. They also have a render method, which defines the JSX that is rendered to the screen. Class components are used when you need to store or modify state, or when you need to use lifecycle methods such as componentDidMount or shouldComponentUpdate.
Functional components, on the other hand, are simple functions that take in props and return JSX. They do not have state or lifecycle methods, and they are typically used for presentational components that do not need to store or modify data.
Here is an example of a class component:
class MyComponent extends React.Component {
state = {
count: 0
};
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
And here is an example of a functional component:
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
}
In general, you should use functional components whenever possible, as they are simpler and easier to write. However, there are cases where you will need to use class components, such as when you need to store or modify state or use lifecycle methods. It's important to understand the differences between the two types of components so that you can choose the right one for your specific use case.
Top comments (2)
Since React 16.8 (React hooks) you do not need class components at all anymore. You can write everything as functional components with hooks like
useState
to manage state.Exactly! Also @timothymureithi, you have not shown an example of state management in your code snippet for functional components. It can be misleading, as functional components also allow you to manage state, actually in a much cleaner way with
useState
, as @brense mentioned.Also, functional components:
this
keyword.Generally youβll want to use functional components instead of class-based ones.