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
Writing several effects in the same component?
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
Effects don’t support async functions (you can’t return a promise).
It’s so annoying, let’s try to solve it:
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
It’s really stupid to implement your own debounce when there is a ton of libraries out there who already have. Right?!
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….
You might think that `useReducer` is better than `useState` when managing a complex object:
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
You’ve probably heard many times that it’s impossible to bail out of rendering if you’re using Context.
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?!