React Class features vs. Hooks equivalents

Nir Hadassi
Dec 25, 2018 · 2 min read
Image for post
Image for post

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

State

ComponentDidMount

ComponentWillUnmount

ComponentWillReceiveProps \ ComponentDidUpdate

DOM refs

this.myVar

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):

ShouldComponentUpdate

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 😉

Soluto Engineering

Engineering. Data. New Technologies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store