Comparing React functional and Class Components
Today React is at version 17.0 and over 40% of developers choose to use React as their primary framework of development. This leads to solving the same problem in many ways. Each one of us is going to have different opinions about why we should solve a problem in a certain way. Recently I started learning React and encountered one such scenario. My dilemma was choosing between class and functional components for my personal project. This is why I started finding out what are the differences between them and what to prefer. This post summarises what I found on comparing functional and class components.
React.component. Class components must have a
render() method on them which renders the markup. Let us take a look at the examples to understand better.
In today’s dynamic web page era, we constantly need to check if the web page is updated and what is updated on the web page. This is where lifecycle hooks come in. Lifecycle hooks provide us with a way to execute code when components render, re-render, or unmounts.
Earlier, functional components were just stateless components that take props and render JSX. So they did not stand any chance in this category. But with React hooks on hand, almost every lifecycle method is possible in functional components as well.
Let us look at some code on how to handle lifecycle events in functional and class components. Some of the key advantages with Functional components in this category are:
- Fewer lines of code
- Related logic like subscribing and unsubsribing (to APIs or other resources) can be kept together.
A developer wrote about measuring performance differences between functional and class components. The experiment includes rendering 1000 components of each type. You can check out the article here: https://itnext.io/react-component-class-vs-stateless-component-e3797c7d23ab and the experiment results here: https://jsfiddle.net/69z2wepo/136096/