内容简介: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
Top 11 recommended ReactJS custom Hooks — with examples.
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.
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 thelocalStorage.
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
@rehooks/document-title
React hook for updating document-title
www.npmjs.com
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
@rehooks/network-status
React hook to track Network status
www.npmjs.com
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:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。