React : Class vs Function Components
Sidhartha Mallick
Posted on January 13, 2022
In the last post, we learned about components. Here, We will learn about types of components.
So, there are 2 types of components as you would have guessed by now.
- Class
- Functional
You can do everything in using either of them. But, functional components are preferred, for obvious reasons.
A simple comparision, why functional component ?
We will write a simple counter, which increments the count value when clicked.
using Function Component, the code as follows -
const FunctionalComponent=()=>{
const[count , setCount]=useState(0);
return
<div style={{margin:'10px'}}>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
)
}
While using Class Component, ... i will leave it upto you to judge.
class ClassComponent extends React.Component{
constructor(){
super();
this.state={
count :0
};
this.increment=this.increment.bind(this);
}
increment(){
this.setState({count : this.state.count +1});
}
render(){
return (
<div style={{margin:'10px'}}>
<h2> {this.state.count}</h2>
<button onClick={this.increase}>+</button>
</div>
)
}
}
and React.Component class comes with a lot of predefined baggage, which are not necessary all the time.
Whereas, by using Functional Components you can customise stuffs as per your need with the help of React Hooks
.
Hooks are my favourites in the whole React library. And one of my fav. hooks in useMemo
.
The hooks come in handy when you are dealing with frequent changes in the data stream.
I found a great use of useMemo
during pagination. It can memoize the component based on the page based on it's parameters. A network call might happen in the background, but it sure hell doesn't concern the user. Hence, improving the UX.
useEffect
hook is used instead of componentDidMount
in a class component.
NOTE : You cannot use hooks inside class components. Hooks are exclusive to function components only.
TIP : Learn to harness the power of custom hooks. They are on a whole different level.
Resources :
Read more about their differences at gfg.
Read more about hooks at @this is my blog
Posted on January 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.