DEV Community

Cover image for The Definitive React Hooks Cheatsheet

The Definitive React Hooks Cheatsheet

Antonin J. (they/them) on April 08, 2019

React Hooks is the new hotness in the React world. I'm writing steadily more and more of them and I thought it would be useful to have a cheatsheet...
Collapse
 
learnwithparam profile image
Paramanantham Harrison

Thanks man. Are you sure about naming with ‘use’?
I don’t think it’s mandatory, you can create any named function as hooks. Probably this might be the recommended way same as how HOC are made with ‘with’ prefix

Collapse
 
camilomejia profile image
Camilo Mejía

The React team provide an ESLint plugin that prevents incorrect usage of hooks, but you must name them with use.

reactjs.org/docs/hooks-faq.html#wh...

Collapse
 
learnwithparam profile image
Paramanantham Harrison

Yeah I got it, thanks for the link

Collapse
 
claudiobernasconi profile image
Claudio Bernasconi

It's a suggestion by the React team - a best practice to make the intent clear.

Collapse
 
antjanus profile image
Antonin J. (they/them)

Interesting. I guess I haven't tested it but it's straight from their docs:

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks

Collapse
 
juliang profile image
Julian Garamendy

Hi Antonin, Thanks for writing this. I think it's very useful.

I have one comment regarding your useUser hook. I think it's important to "cancel" the request before the component unmounts to avoid memory leaks.
I wrote about it a few days ago. You might want to have a look:
dev.to/juliang/cancelling-a-promis...

Cheers!

Collapse
 
guico33 profile image
guico33

In this case there's no memory leak though.
It's simply a warning as updating the state will effectively do nothing after the component has been unmounted.

Collapse
 
juliang profile image
Julian Garamendy

Ah. I see your point. I suppose the dangling reference to the component gets garbage-collected after the promise resolves and state is updated?

Collapse
 
bbarbour profile image
Brian Barbour

Is it possible to use a custom hook in place of something like a render prop or a higher order component?

Collapse
 
kayis profile image
K • Edited

Yes, that was one of the use-cases they had in mind when creating hooks.

Collapse
 
bbarbour profile image
Brian Barbour

Awesome. I now I need to practice and figure out how to do that.

Collapse
 
httpjunkie profile image
Eric Bishard

Nice article, I like the useReducer code sandbox example, pretty straight forward. I follow a similar template in my "Guide to Learning React Hooks article", you should check it out.

Collapse
 
rohovdmytro profile image
Rohov Dmytro • Edited

Thanks for an article.

Another great place to wrap a head around hooks is Dan's blog.

Collapse
 
antjanus profile image
Antonin J. (they/them)

Dan's blog is awesome.