十大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>
);
}