5 ways that will change how you write React hooks

NOTE!
Tips and methods in this post are my own personal preference, and I’m sure many people will disagree.
There is no right or wrong. Every approach has its pros and cons. If you take just one good thing out of the post — I’ve done my share.
I do not mean to insult anyone who thinks differently. Some of the “bad code” examples used to be code that I’ve written myself!
If you do think differently — you are more then welcome to comment and change my mind.

Good reading!

An Effect has no Name

I don’t want to read your code just to know what they are doing… duh…

Here’s a tip for you, use named functions:

Much better right?
There’s another benefit — you will see the effect name in React dev tools:
https://dev-to-uploads.s3.amazonaws.com/i/sed4i1lvfjt4ahabfgn7.png

Don’t be a smarty pants and try to extract to constants, like this:

Because then you are only fooling the linter, not me!
(Exhaustive deps rules won’t work for the function implementations)

Async Functions

WTF?! IIFE?! Are we in 2010?!

Try again please:

No! You are not listening! (See comment above about exhaustive deps)

OK, I’ll give it to you:

Sometimes you just gotta be verbose with them code.

Or, if you insist on taking the function out, take it out completely from the component and pass it the deps:

Debouncing the Hooks Way

Wrong! ’Cause now we got hooks!!

Ummm…. what?
Yes, that is an implementation of debounce with nothing but effect, timeout and cleanup function. You’re smart, think about it.

useCallbacks? Nahhh….

But think about it, you will still have to use `useCallback` for each action dispatch if you want a stable ref:

Think about this version instead:

All actions are memoized!
And no switch case, meaning better debugging experience and clearer TypeScript integration.

Use `useContext` with selectors to bail out of render

Well…..
You’re right. I’ll give it to you.

But cross your fingers, ’cause selectors are coming to a version near you:
https://github.com/reactjs/rfcs/pull/119

When this is accepted, we would be able to do this:

Hopefully in the next few months, but who knows, right?!

Hope you learned something new! Tell your friends.

--

--

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