React Functional v/s Class Components
19 January, 2023
0
0
0
Contributors
Introduction
In React, you can define components either as a function or as a class. These two types of components are known as functional and class components, respectively. When React first came out, the class component were the goto standard to build them because the class methods inherited from the React
class provided all the functionality necessary. But, with the introduction of hooks in React, the lines between the functionality of a Class component and a functional component got blurred because all those things could now be accomplished in functional components as well.
Functional component
Functional components are simpler and easier to write than class components. They are essentially just JavaScript functions that accept props as an argument and return JSX. They don't have state or lifecycle methods, so they are easier to understand and debug. Here's an example of a functional component:
import React from 'react';
function MyComponent(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>Welcome to my component.</p>
</div>
);
}
Class component
Class components are a bit more powerful and flexible than functional components. They can have state, lifecycle methods, and other features that are not available to functional components. Here's an example of a class component:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<h1>Hello, {this.props.name}!</h1>
<p>Welcome to my component. You have clicked the button {this.state.count} times.</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me!
</button>
</div>
);
}
}
When to use?
In general, you should use functional components whenever possible, because they are simpler and easier to understand. However, there are some situations where a class component might be necessary, such as when you need to use lifecycle methods or when you need to store state that is specific to a single component.