推荐十一个React Hook库

开发 前端
在React开发中,保持干净的代码风格,可读性,可维护性,更少的代码行以及可重用性至关重要。本篇文章将向您介绍应立即开始使用的十一个React Hook库。不用再拖延了,让我们开始吧。

 Hooks来了,并在暴风雨中占领了React社区。自最初发布以来已经有一段时间了,这意味着有很多支持库。在搜索与React相关的内容时,很难不说“ hook”。如果你们还没有使用它的话,应该尽快将它们加入代码库。它们将使您的编码生活变得更加轻松和愉快。

在React开发中,保持干净的代码风格,可读性,可维护性,更少的代码行以及可重用性至关重要。本篇文章将向您介绍应立即开始使用的十一个React Hook库。不用再拖延了,让我们开始吧。

1.use-http
use-http是一个非常有用的软件包,可用来替代Fetch API。以高质量编写和维护。它使您的编码更简单易懂,更精确地讲是数据处理部分。hook本身使用TypeScript,甚至支持SSR和GraphQL。它返回响应,加载,错误数据和不同的请求方法,例如Get,Post,Put,Patch和Delete。

它提供的主要功能是:

  • 请求/响应拦截器
  • 支持React Native
  • 卸载组件时中止/取消挂起的http请求
  • 缓存

CodeSandbox示例和Youtube视频以及GitHub自述文件都对此进行了很好的记录。

官网地址:https://use-http.com/#/

使用案例

import useFetch from "use-http" 
 
const Example = () => { 
  const [todos, setTodos] = useState([]) 
  const { get, post, response, loading, error } = useFetch("https://example.com"
 
  useEffect(() => { get("/todos") }, []) 
 
  const addTodo = async () => { 
      await post("/todos", { title: "example todo" }); 
      if (response.ok) setTodos([...todos, newTodo]) 
  } 
 
  return ( 
    <> 
      <button onClick={addTodo}>Add Todo</button> 
      {error && 'Error!'
      {loading && 'Loading...'
      {todos.map(todo => ( 
        <span key={todo.id}>{todo.title}</span> 
      )} 
    </> 
  ); 
}; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

2.useMedia
您是否需要一种跟踪CSS媒体查询的方法?该useMedia hook提供一个简单的方法解决问题。这是一个准确跟踪React sensor hook。媒体查询以及任何应用程序或网站的响应能力都非常重要。

它提供了支持TypeScript编写。该软件包具有定义明确的文档,其中解释了挂钩的用法以及测试方法。

地址:https://github.com/streamich/use-media

使用案例:

import useMedia from 'use-media'
 
const Example = () => { 
  const isWide = useMedia({minWidth: '1000px'}); 
 
  return ( 
    <span> 
      Screen is wide: {isWide ? "WideScreen" : "NarrowScreen"
    </span> 
  ); 
}; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

3.Constate
Constate是一个hook package,可将本地状态提升到React Context。这意味着可以以最小的努力轻松地将任何组件的任何状态提升到上下文。如果您想在多个位置使用相同的状态,或者为多个组件提供相同的状态,这很有用。该名称来自合并上下文和状态的文字游戏。使用Typescript写的,体积很小。虽然该文档不是很详细,但是可以完成工作。

地址:https://github.com/diegohaz/constate

使用案例:

import React, { useState } from "react"
import constate from "constate"
 
// custom hook 
function useCounter() { 
  const [count, setCount] = useState(0); 
  const increment = () => setCount(prevCount => prevCount + 1); 
  return { count, increment }; 

 
// hook passed in constate 
const [CounterProvider, useCounterContext] = constate(useCounter); 
 
function Button() { 
  // use the context 
  const { increment } = useCounterContext(); 
  return <button onClick={increment}>+</button>; 

 
function Count() { 
  // use the context 
  const { count } = useCounterContext(); 
  return <span>{count}</span>; 

 
function App() { 
  // wrap the component with provider 
  return ( 
    <CounterProvider> 
      <Count /> 
      <Button /> 
    </CounterProvider> 
  ); 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

4.Redux hooks
Redux是许多(即使不是全部)React开发人员的知名工具。在整个应用程序中,它用作全局状态管理器。在React的最初版本发布几个月后,它就随钩而上了。它通过现有connect()方法提供了HOC(高阶组件)模式的替代方法。

提供的最著名的hooks是:

  • useSelector
  • useDispatch
  • useStore

该文档非常好,有点复杂,但是它将为您提供开始使用它们所需的任何信息。

地址:https://github.com/reduxjs/redux

使用案例:

import {useSelector, useDispatch} from "react-redux"
import React from "react"
import * as actions from "./actions"
 
const Example = () => { 
const dispatch = useDispatch() 
const counter = useSelector(state => state.counter) 
 
return ( 
<div> 
   <span> 
     {counter.value} 
   </span> 
   <button onClick={() => dispatch(actions.incrementCounter)}> 
     Counter +1 
   </button> 
</div> 
); 
}; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

5.React hook form
React hook form是一个与Formik和Redux表单相似的表单校验hook库,但是更好!凭借其更简单的语法,速度,更少的转译和更好的可维护性,它开始爬上GitHub的阶梯。它的体积很小,并且考虑到性能而构建。该库甚至提供了它的表单生成器,这很棒!它是React钩子库(14.8k)中GitHub启动数量最多的平台之一。

它提供的主要功能:

  • 非受控表单校验
  • 以性能和开发体验为基础构建
  • 迷你的体积而没有其他依赖
  • 遵循 html 标准进行校验
  • 与 React Native 兼容
  • 支持浏览器原生校验

地址:https://github.com/react-hook-form/react-hook-form

使用案例:

import React from "react"
import { useForm } from "react-hook-form"
 
function App() { 
  const { register, handleSubmit, errors } = useForm(); 
  const onSubmit = (data) => { 
    // logs {firstName:"exampleFirstName", lastName:"exampleLastName"
    console.log(data); 
  }; 
 
  return ( 
    <form onSubmit={handleSubmit(onSubmit)}> 
      <input name="firstName" ref={register} /> 
      <input name="lastName" ref={register({ required: true })} /> 
      {errors.lastName && <span>"Last name is a required field."</span>} 
      <input name="age" ref={register({ required: true })} /> 
      {errors.age && <span>"Please enter number for age."</span>} 
      <input type="submit" /> 
    </form> 
  ); 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

6.useDebounce
useDebounce 表示一个用于去抖的小钩子。它用于将功能执行推迟到以后。常用于获取数据的输入和表格中。

地址:https://github.com/xnimorz/use-debounce

使用案例:

import React, { useState } from "react"
import { useDebounce } from "use-debounce"
 
export default function Input() { 
  const [text, setText] = useState("Hello"); 
  const [value] = useDebounce(text, 1000); 
 
  return ( 
    <div> 
      <input 
        defaultValue={"Hello"
        onChange={(e) => { 
          setText(e.target.value); 
        }} 
      /> 
      <p>Value: {text}</p> 
      <p>Debounced value: {value}</p> 
    </div> 
  ); 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

7.useLocalStorage
useLocalStorage是一个小钩子,与上面的钩子一样。这对于在localStorage中提取和设置数据非常有用。操作变得容易。提供跨多个选项卡的自动JSON序列化和同步,并以TypeScript编写,因此它提供了类型。

文档以高质量的方式编写,并且可以通过扩展示例来很好地理解。

地址:https://github.com/rehooks/local-storage

使用案例:

import React, { useState } from "react"
import { writeStorage } from '@rehooks/local-storage'
 
export default function Example() { 
  let counter = 0; 
  const [counterValue] = useLocalStorage('counterValue'); 
 
  return ( 
    <div> 
      <span>{counterValue}</span> 
      <button onClick={() => writeStorage('i', ++counter)}> 
        Click Me 
      </button> 
    </div> 
  ); 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

8.usePortal
usePortal 使创建下拉菜单,模态,通知弹出窗口,工具提示等变得非常容易!它提供了在应用程序的DOM层次结构之外创建元素的信息(react docs)。该钩子与SSR一起使用,因为它是同构的。用TypeScript编写并具有内置状态。它还提供了portals样式和大量其他选项的完全定制。

为此编写的文档非常好,其中显示了许多示例,这些示例对于开始使用库/自己做钩子来说绰绰有余。

地址:https://github.com/alex-cory/react-useportal

使用案例:

import React, { useState } from "react"
import usePortal from "react-useportal"
 
const Example = () => { 
    const { ref, openPortal, closePortal, isOpen, Portal } = usePortal() 
 
    return ( 
      <> 
         <button ref={ref} onClick={() => openPortal()}> 
            Open Portal 
         </button> 
          {isOpen && ( 
            <Portal> 
              <p> 
                This Portal handles its own state.{' '
                <button onClick={closePortal}>Close me!</button>, hit ESC or 
                click outside of me. 
              </p> 
            </Portal> 
          )} 
       </> 
 ) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

9.useHover
useHover是一个React state hook,它确定是否正在hover React元素。简单易用。该库很小,易于使用,但如果您有足够的创造力,它可能会很强大。

它还提供了悬停效果的延迟。支持TypeScript。文档没有那么详细,但是它将向您展示如何正确地使用它。

地址:https://github.com/andrewbranch/react-use-hover

使用案例:

import useHover from "react-use-hover"
 
const Example = () => { 
  const [isHovering, hoverProps] = useHover(); 
  return ( 
    <> 
      <span {...hoverProps} aria-describedby="overlay">Hover me</span> 
      {isHovering ? <div> I’m a little tooltip! </div> : null
    </> 
  ); 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

10.React router hooks
React router hooks是React最受欢迎的库之一。它用于路由和获取应用程序URL历史记录等。它与Redux一起实现了用于获取此类有用数据的hook。

它提供的主要功能是:

useHistory
useLocation
useParams
useRouteMatch
它的名字很不言自明。UseHistory将获取应用程序历史记录和方法的数据,例如push推送到新路由。UseLocation将返回代表当前URL的对象。UseParams将返回当前路径的URL参数的键-值对的对象。最后,useRouteMatch将尝试将当前URL与给定URL进行匹配,给定URL可以是字符串,也可以是具有不同选项的对象。

文档很好,写了很多例子

地址:https://github.com/ReactTraining/react-router

使用案例:

import { useHistory, useLocation, useRouteMatch } from "react-router-dom"
 
const Example = () => { 
let history = useHistory(); 
let location = useLoction(); 
let isMatchingURL = useRouteMatch("/post/11"); 
 
function handleClick() { 
    history.push("/home"); 

 
return ( 
    <div> 
        <span>Current URL: {location.pathname}</span> 
        {isMatchingURL ? <span>Matching provided URL! Yay! </span> : null
        <button type="button" onClick={handleClick}> 
            Go home 
        </button> 
</div> 
); 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

11.react-use
react-use是一个必不可少的 React Hooks集合.你需要安装React 16.8.0或更高版本才能使用Hooks API。

地址:github.com/streamich/react-use

使用案例:

import {useBattery} from 'react-use'
 
const Demo = () => { 
  const state = useBattery(); 
 
  return ( 
    <pre> 
      {JSON.stringify(state, null, 2)} 
    </pre> 
  ); 
}; 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

当前还有更多的钩子库,找到适合自己使用的就是最好的,不仅提高了开发的效率,而且让代码更加整洁,简单。

 

责任编辑:姜华 来源: 小丑的小屋
相关推荐

2011-08-11 13:30:04

云计算开源

2017-06-15 17:50:06

编程机器学习开发

2010-09-08 12:55:34

CSS

2011-07-14 09:38:13

2016-08-12 08:24:56

GitLab Flowmastertags版本

2010-04-29 14:41:09

SharePoint

2020-10-28 09:37:08

React代码数据

2015-09-16 10:48:57

Python

2010-08-11 13:54:41

Windows 7运行

2021-08-13 15:32:09

elementary Linux

2020-07-03 11:29:22

内包IT领导者数字化转型

2022-06-07 08:20:49

线程安全多线程

2022-02-21 13:27:11

接口性能优化索引命令

2021-07-19 13:52:17

分析工具软件大数据

2016-02-16 17:38:40

2011-07-19 16:56:09

移动Web编程工具框架

2020-03-02 15:54:20

科技公司数据信任

2021-12-06 10:40:01

One-Liner代码前端

2021-12-15 21:00:27

人工智能AI文案

2021-05-14 09:49:47

React HookReact应用
点赞
收藏

51CTO技术栈公众号