Are there still use cases for React Class components?
The answer is certainly yes.
This post was motivated by a recently lash of tweets complaining at how hooks introduce unnecessary complexity, and that the Class component model was easier to understand due to its clear lifecycle methods.
Albeit hooks became wildly popular, no one in the React core team ever mentioned removing class components so it is still a viable option to create apps just with class components.
Futhermore, there are cases where only a class component would actually solve the problem. Let’s see them.
The React documention does such a wonderful job at explaining error boundaries that I will just link you to it = )
Running Logic Connected To a Next DOM Update
In React v16.3.0 the Core team added a lifecycle called
getSnapshotBeforeUpdate that didn’t get much attention from everyone.
Add a new getSnapshotBeforeUpdate() lifecycle. (@bvaughn in #12404)
But this lifecycle is useful for layout animations, restoring scroll positions, and focus management.
@sebmarkbage) mentions the following on a recent tweet:
This is useful for things like layout animations, restoring scroll position and can be used for focus management (e.g. figuring out where to move focus after something is deleted based on where it was before it got deleted).
It has a guarantee to run before the
componentDidUpdate plus pass the return value to the
componentDidUpdate's third argument:
Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate()
You could possibly recreate this with useLayoutEffect since it also runs in the updating phase before the DOM mutations are actually painted.
Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.
If you have any other use cases for
getSnapshotBeforeUpdate tweet at me = ).
If You Don’t Like Hooks = D
Is there anyone left outside of Facebook who still likes hooks?
And maybe you don’t like hooks mental model. You can always use classes 😅.
While reviewing code submissions at G2i, I actually have ran into a few candidates that argued exactly this.