热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

11UsefulCustomReactHooksforYourNextWebApp

CustomhooksleveragethepowerofReacthookstoaddadditionalfunctionalitytoourReactapps.SincethereleaseoftheReactHooks,therehasbeenanexplosivegrowthofcustomhooks,thousandsofReactdevsallovertheworldhavechurn

Top 11 recommended ReactJS custom Hooks — with examples.

Chidume Nnamdi :fire::computer::musical_note::video_game:

Follow

Mar 26 ·6min read

11 Useful Custom React Hooks for Your Next Web App

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.

11 Useful Custom React Hooks for Your Next Web App
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:

  • https://react-custom-hooks-ex.stackblitz.io
  • My Demo app’s source code on Github

1. useClippy

use-clippy

useClippy is a TypeScript-friendly React hook for reading from and writing to the user's clipboard. Not to be confused…

www.npmjs.com

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

react-window-communication-hook

React hook to communicate among browsers contexts (windows, tabs, iframes). Example use case: When the user presses…

www.npmjs.com

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

react-script-hook

React hook to dynamically load an external script and know when its loaded

www.npmjs.com

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

@rehooks/local-storage

React hook for enabling synchronization with local-storage. API Docs can be found here. This can be anywhere from…

www.npmjs.com

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

react-use-idb

React side-effect hook that manages a single indexDB item. A drop-in remplacement over useLocalStorage. LocalStorage is…

www.npmjs.com

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

use-mouse-action

React Hooks to listen to both mouse down or up and click events with a once called function. This hook can be used to…

www.npmjs.com

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

@rehooks/online-status

React hook for subscribing to `online`/`offline` events and the `navigator.onLine` property to see current status

www.npmjs.com

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

react-speech-kit

React hooks for in-browser Speech Recognition and Speech Synthesis. Demo here A full example can be found here. The…

www.npmjs.com

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

react-speech-kit

React hooks for in-browser Speech Recognition and Speech Synthesis. Demo here A full example can be found here. The…

www.npmjs.com

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:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 我们


推荐阅读
author-avatar
1157476701qq
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有