11 Useful Custom React Hooks for Your Next Web App

Top 11 recommended ReactJS custom Hooks ā€” with examples.

Chidume Nnamdi šŸ”„šŸ’»šŸŽµšŸŽ®
Bits and Pieces

--

Custom hooks leverage the power of React hooks to add additional functionality to our React apps. Since the release of the React Hooks, there has been an explosive growth of custom hooks, thousands of React devs all over the world have churned out hundreds of custom hooks that simplify most of the arduous and boring tasks we do in React projects.

ā€œUncommon thinkers reuse what common thinkers refuseā€

-J. R. D. Tata

In the same ā€œspirit of React Hooksā€, make sure you donā€™t waste your time doing boring repetitive work. Make use of cloud component hubs like Bit.dev to ā€œharvestā€ reusable components from your different projects and share them to your own component collection at Bit.dev. Itā€™s a great way for you and your team to maximize code reuse and speed up development.

Browsing through shared React components @ bit.dev

See them in nature ā€” a demonstration of Hooks

Iā€™ve built a React demo project to demonstrate all the custom hooks in this post. You can play live with the demo examples there. See link below:

1. useClippy

A hook for copying data to the clipboard and retrieving/pasting it using Ctrl-C/Command-C and Ctrl-V/Command-V.

Example:

In the above example, we destructure the useClippy to clipboard and setClipboard. clipboard is the data in the clipboard and setClipboard sets the data in the clipboard.

2. useBrowserContextCommunication

useBrowserContextCommunication uses the Broadcast Channel API to deliver an easy solution for communication between different browser contexts (tabs, iframes, windows).

To use it ā€”

import useBrowserContextCommunication from "react-window-communication-hook"

Pass a channel name to the hook (just as you would with the Broadcast Channel API) ā€”

const [communicationState, postMessage] = useBrowserContextCommunication("politicsChannel");

It returns an array that has two items. The first is a communication state. This state contains lastMessage and messages which is an array of the messages that were sent from other tabs/windows to the current one. The second item is a function used to send messages to the other context.

3. useScript

useScript is a hook for loading (and notifying when theyā€™re loaded) external scripts, dynamically.

Example:

In this example, we want to add analytics to our component by loading this external script using useScript.

The load property indicates when the external script is done loading. We check the loading and error flag to display messages accordingly.

4. useLocalStorage

This hook simplifies the storage and retrieval of data from the localStorage.

Install the library:

npm i @rehooks/local-storage

import it like so:

import { useLocalStorage } from "@rehooks/local-storage"

useLocalStorage is called with a key name. useLocalStorage returns three items in an array. The first is the value of the key name sent, the second is a function to set a new value to the key, and the third is a function to delete the key/value pair.

Example:

The name will be the key where we can put the value. The name is the initial value of the key, the setName will set the value in the name key, the deleteName will delete the value of the name key.

5. useIdb

UseIdb uses the IndexedDB storage in the browser to store data. IndexedDB is not as popular or as known as its counterpart localStorage but it definitely shouldnā€™t be overlooked.

IndexedDB is ā€œa low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this dataā€ (MDN).

To use it ā€”

npm i react-use-idb

Example:

We set a database with the key user and with an initial value of the user details in an object. The useIdb returns an array that we destructure to extract the value and the update function, as user and setUser, respectively.

We render the user and set a button to update the user age to 26 when clicked by calling the setUser function.

This setUser will update the user object and re-render the component.

6. use-mouse-action

A library with three React hooks for listening to mouse events on an element or JSX element.

useMouseAction: This is used to register mouse actions on an element.

useMouseDown: This is used to register a mouse down event on an element.

useMouseUp: This registers a mouse up event on an element.

Yo use it, destructure the hooks from the library:

import { useMouseAction, useMouseDown, useMouseUp } from "use-mouse-action"

Example:

The Mouse Action button registers the click, down and up event. It will display the "Mouse clicked" message when we click on it.

The ā€œMouse Downā€ button registers only the onmousedown event on it. So when we click on it first the ā€œMouse downā€ message is printed on the console.

The ā€œMouse Upā€ button registers the onmouseup event on it. So when we click it and release it, the ā€œMouse Upā€ will be printed on the console.

7. useOnlineStatus

useOnlineStatus uses the navigator.onLine property to check the network status to determine if the user is connected to the internet or not.

useOnlineStatus returns a boolean value (true/false for ā€˜onlineā€™/ā€™offlineā€™)

Example:

Here, we use the ternary operator to display ā€œOnlineā€ if online or ā€œOfflineā€ if offline.

8. useDocumentTitle

As you probably know, routing in React apps doesnā€™t automatically update the page title (shown in the browserā€™s tabs). useDocumentTitle hook helps to solve exactly that.

Example:

9. useNetworkStatus

useNetworkStatus hook exposes the navigator.connection object properties to indicate the network status:

  • downlink
  • effectiveType (checks if the user has a slow network or not)
  • rtt
  • saveData (A boolean value that tells if the browser is on data-saver mode)

Example:

The above code simply displays the network status of the user using the useNetworkStatus hook.

10. useSpeechSynthesis

This hook uses the Web Speech API to make text-to-sound synthesis easy to use in our React app.

This hook can be found in the react-speech-kit:

npm i react-speech-kit

and imported like so:

import { useSpeechSynthesis } from "react-speech-kit"

The useSpeechSynthesis returns an object with speak function.

Example:

In the example above, we use ref to get the HTML instance of the input[type=ā€textā€]. When we click the Speak button we call the speak function from the ; hook and pass an object, the object holds a text property which is the text typed in the input box. This will cause the OS to speak out the text.

11. useSpeechRecognition

This is used for sound-to-text translation. This hook uses the Web Speech API to convert sound to text in our React app.

It is part of the react-speech-kit and can be installed and imported like so:

npm i react-speech-kitimport { useSpeechRecognition } from "react-speech-kit"

The useSpeechRecognition returns an object that contains:

listen: a function that tells the browser to listen for audio coming from the mic.

listening: a boolean value that indicates the browser is listening for input in the mic.

stop: a function that cancels listening for input coming from the mic.

Example:

Get my eBook

I have written an eBook that explains a lot of JavaScript concepts in simpler terms with reference to the EcmaSpec as a guide:

Thanks for stopping by my little corner of the web. I think youā€™ll love my email newsletter about programming advice, tutoring, tech, programming and software development. Just sign up below:

Check out this new API tool:

Learn More

--

--

JS | Blockchain dev | Author of ā€œUnderstanding JavaScriptā€ and ā€œArray Methods in JavaScriptā€ - https://app.gumroad.com/chidumennamdi šŸ“•