React Class features vs. Hooks equivalents

Nir Hadassi
Dec 25, 2018 · 2 min read

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 by asurion

Engineering. Product. UX. Culture.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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