Class Vs Functional React Component ~ Tricky Closure Problem

Andreas Sujono
5 min readMar 27, 2023

Do you think class and functional component behaves the same way? think again

When hooks are introduced in 2018, many people think they should migrate from class components to functional components straight away. However, it’s not recommended to convert your previous class component codebase fully to a functional component with hooks because the behaviour might change. I, personally love hooks as they are so simple yet powerful. However, I found some problem in hooks that is quite tricky to solve. I will discuss that at the end of this article.

General Difference

Previously, a functional component could just handle a static and non-reactive component, meaning features such as state and component lifecycle are not available in a functional component. However, hooks are finally introduced as the solution. Almost all the things that you can do in the class component can be done in a functional component. Only 1 feature that is not available now yet which is the error handler. Only the class component can catch the UI error by using componentDidCatch and static getDerivedStateFromError

Before we dive into the difference between those 2 component types, we need to know why hooks are preferred and recommended by the React team:

--

--

Andreas Sujono

A Full Stack Developer with 5 years of working experience, Web2 and Web3 Enthusiast, twitter: @AndreasSujono2