Lesson 1: The ABCs of React Hooks
React Hooks are like alphabet soup - it's easy as A, B, C!
Posted on December 22, 2021
Note: this is part of a larger series, "Clean React TypeScript Hooks". If you're interested, check out the series overview.
Blog readers, it's come to my attention that far too many devs get mucked down in new languages, syntax, tools, and endless engineering debates while skipping a critical lesson: learning the very basic concepts. So here is my remedy (or attempt) at correct that problem, at least for React hooks. Through a handful of lessons, I'm going to teach you how to write super clean, super cool React Hooks using TypeScript. But again, we're going to start with the basics, and you can't get much more basic than the ABC's.
So here's where we'll start: Describing all the React Hooks using the ABC's.
What's A React Hook?
Before getting to the ABC's of React Hooks, I probably should first define what a React Hook is:
I'll do my version first:
a React Hook is a function that takes input and returns output
And for completeness, React's official description:
Hooks let you use state and other React features without writing a class.
(and yes, the official documentation capitalizes the 'H' in 'Hooks', so I'll be following their lead.)
That's it.
Seems too simple right? I'll prove it, explaining each React Hook with our beloved ABC's.
useState In ABC's:
Give me a value A and setter function B, where I want my initial value of A to be C
const [A, B] = useState(C)
useEffect In In ABC's:
Run function D when E changes
useEffect(() => {
D()
}, [E]
but we of course note useEffect()
seems to have an array for the "when E changes" part, so let's imagine we have also a value F
we want to detect changes in. Well, simply add this to the change array:
Run function D when E or F changes
useEffect(() => {
D()
}, [E, F]
Want to run function D
when nothing changes? That's fine too, just empty out your dependency array. The change here is then implicit, in that it will only fire once, when the hook mounts. This is the equivalent of the (now infamous) componentDidMount
:
Run function D on mount
useEffect(() => {
D()
}, []
So, you may be asking, well if there is a hook equivalent for componentDidMount
, there certainly should be one for componentWillUnmount
, right? Yep! This is done by using return
in useEffect
. Let's add more letters to our alphabet, this time a function G
:
Run function G on unmount
useEffect(() => {
return G()
}, []