React Class features vs. Hooks equivalents
I gave a talk during a recent meetup at Soluto HQ — Intro to React Hooks.
While preparing for the presentation, I fell completely in love with Hooks.
Although I was skeptical at first glance, I quickly realized how easy it is to use them and how they make perfect sense.
You can really tell how much thought was put into the API and how it solves real life problems.
You can find a video of my talk attached to this post (Hebrew only… Sorry!).
In my talk I explained why we need Hooks, how they work, went over the core Hooks (useState, useEffect, useRef and useContext) and showed how to convert some of the class features into Hooks.
I also covered some other new features — memo, lazy and Suspense.
If you don’t speak Hebrew or just prefer reading over watching, I made a TL:DW (kind of a cheat sheet) on class features vs. Hooks. Enough intros… Let’s jump right to business!
Class features vs. Hooks equivalents
ComponentWillReceiveProps \ ComponentDidUpdate
useRef has another cool usage besides DOM refs, it is also a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
Handy, for example, to keep an interval id:
Comparing with the previous state\props
Some lifecycle method, like componentDidUpdate, provide the previous state and props.
If you really need the previous values for your Hooks, this can be imitated the following way (using yet again our good friend — useRef):
We gonna use memo for this one, while this is not a Hook, it’s still part of the class-to-functional-component migration plan:
And that is React Hooks in a nutshell. I hope you will find this helpful when writing your next functional component.
Needless to say (but I’ll say it anyway), there are a whole lot more interesting and cool ways to use Hooks. I urge you to read the awesome overview the React team posted. Don’t miss out the FAQ section!
Last but not least, here’s me in my meetup video about React Hooks.
Watch, Like, Subscribe 😉