Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 20, 2020 10:21 am GMT

Illustrated Notes on Custom React Hooks

CustomHooks_DevTo_1

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.

CustomHooks_DevTo_2

CustomHooks_DevTo_3

CustomHooks_DevTo_4

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.

CustomHooks_DevTo_5

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.

CustomHooks_DevTo_6
CustomHooks_DevTo_7

Creating Your Own Custom Hooks

CustomHooks_DevTo_8

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.

CustomHooks_DevTo_9

CustomHooks_DevTo_10

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.

CustomHooks_DevTo_11

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.

CustomHooks_DevTo_12

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!

shareable-custom-hooks-in-react

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!


Original Link: https://dev.to/egghead/illustrated-notes-on-custom-react-hooks-5b4a

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To