Illustrated notes on Joe Previtte's course on Building Custom React Hooks on egghead
The Basics of React Hooks
If you're not up to speed on React hooks, here's a very quick overview...
Hooks let us do more than just display static UI components. They give us the ability to hold state in our components, and use lifecycle events that can handle side effects and data changing over time.
We used to do this with class components, but the React library added hooks in early 2019 with version 16.8.
The Two Main Hooks
The React library comes with a set of "build in" hooks. There are 10 official hooks, but the two most common ones are useState and useEffect.
1. useState
useState lets us hold "state" – a piece of data that changes over time while your app is up and running.
2. useEffect
useEffect let's us perform side effects. That means we can execute functions or run code that isn't directly about rendering UI elements to the DOM.
This includes making data requests, or running JavaScript functions after the components have already rendered.
Creating Your Own Custom Hooks
We can also remix these built-in hooks to create custom hooks.
These are simply functions you write that use the basic hooks, and layer extra functionality on top of them.
There's a great collection on usehooks.com if you want to see some examples.
Once you've written your hook, there's a handy create-react-hook library that does all the formatting grunt work and makes uploading your hook to npm easy.
Just use npx create-react-hook
, add a package name, description, Github details, and licence. There's a default template that works for most cases.
It'll generate a series of files and folders for you. You just need to add your hook file to the /src
folder, write the readme, and take care of some other housekeeping.
After that you're all ready to publish your hook for others to use 🎉
Joe's course is nice and short, and covers all the details of how to do this.
You can get a handle on custom hooks in under 30 minutes. Then start writing your own!
👁🗨 If these are hard to read, you can download a free high-res PDF version on the course itself.
Dev.to limits image sizes a lot and it's hard to make it readable on here. Apologies!
Top comments (5)
Love the illustrations
Damn, those are amazing!
Very well illustrated...!
Amazing! Thanks for sharing.
Why create one when you can get all awesome hooks in a single library?
Try scriptkavi/hooks. Copy paste style and easy to integrate with its own CLI