【译】值得推荐的十大React Hook 库

前端开发 作者: 2024-08-20 13:35:01
十大React Hook库 原文地址:https://dev.to/bornfightcompany/top-10-react-hook-libraries-4065 原文作者:Juraj Pavlo

十大React Hook库

它提供的主要功能是:

  • 请求/响应拦截器
  • 暂停(目前处于实验状态)
  • 重发功能
  • 缓存
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>
      )}
    </>
  );
};
import useMedia from 'use-media';

const Example = () => {
  const isWide = useMedia({minWidth: '1000px'});

  return (
    <span>
      Screen is wide: {isWide ? "WideScreen" : "NarrowScreen"}
    </span>
  );
};
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>
  );
  • useSelector
  • useDispatch
  • useStore
import  {useSelector,useDispatch} from "react-redux";
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>
);
};
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>
  );
}
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>
  );
}
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>
  );
}
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>
          )}
       </>
 )
}
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}
    </>
  );
}
  • useHistory
  • useLocation
  • useParams
  • useRouteMatch
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>
);
}
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65539.html