Before the introduction of Hooks in React, functional components were called stateless components and were behind class components on feature basis. After the introduction of Hooks, functional components are equivalent to class components.
Although functional components are the new trend, the react team insists on keeping class components in React. Therefore, it is important to know how these both components differ.
On the following basis let’s compare functional and class components:
- Decalaration
Functional components are nothing but JavaScript functions and therefore can be declared using an arrow function or the function keyword:
function card(props){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
const card = (props) =>{
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
Class components on the other hand, are declared using the ES6 class:
class Card extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
}
- Handling props
Let’s render the following component with props and analyse how functional and class components handle props: