So In this blog, we are going to understand the major difference between class components and functional component
- So when React was introduced to the web dev world, traditional class components were used for creating components. here we have to write some extra code as there was no possibility to pass props directly. As we can see a component structure below
Here we have to use this keyword to manage the states. also, code sometimes seems too complex for beginners.
So when the React 16.8 update came, Hooks were introduced for managing the states within functional components. As we can see the functional component structure below
Functional Components vs Class Components
Functional Components | Class Components |
Functional components are simple JavaScript functions that take props as arguments and return JSX. | A class component extends from React.Component and the render function return the React element. |
It is known as a stateless component since it does not have any state | A class component can also be referred to as a stateful component |
A functional component does not respond to a lifecycle event | Lifecycle events can be handled by class components |
A constructor is not supported by functional components | Provide a constructor for storing state before passing props to the parent class |
React provides useState()Hook for handling state functional components. | It's a bit different for class components. The this keyword is required, along with the setState() function and a constructor. |
Comparatively, functional components perform better than class components | A class component is more complex: it is an instance of React.Component with a constructor. |
Conclusion:
Since Class components are outdated and only used in legacy applications that were created before 2019. Mostly functional components are used everywhere as it is an easy-to-understand and convenient way to manage states.