Class Vs Functional React Component ~ Tricky Closure Problem
--
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:
- Class is confusing for both humans and machines
Javascript is basically not an object-oriented programming language. ES6 mimic the class feature by utilizing a concept called prototypal inheritance. React team also realizes this and announced that class components are difficult to be optimized, for instance, the minification does now work very well. Moreover, The class component also makes hot reload flaky and unreliable
- More complex code in class component
A lot of logic is combined together in component lifecycle methods in class components because we only allow declaring lifecycle method once. However, in functional component, we can call useEffect
multiple times to decouple and localize logic as useEffect
acts as 3 component lifecycle: componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
- code more succinct & low learning curve