A set of reusable react hooks
npm install --save m-hooks
or
yarn add m-hooks
Name | Arguments | Returns |
---|---|---|
useFetch |
url, options | response, error, loading |
useDebounce |
f, time, dependencies | cancel |
useThrottle |
f, time, dependencies | cancel |
useClickInside |
containerRef, f | |
useClickOutside |
containerRef, f | |
useField |
initial | { value, set, reset, bind } |
useTitle |
title | |
useDidMount |
f | - |
useWillUnmount |
f | - |
useDidUpdate |
f, dependencies | - |
useToggle |
initial | { on, set, reset, toggle } |
useHover |
- | { hovered, bind } |
useFocus |
- | { focused, bind } |
import React from 'react'
import { useFetch } from 'm-hooks'
const App = () => {
const { response, loading, error } = useFetch(
'https://jsonplaceholder.typicode.com/todos/1'
)
return (
<div>
<h1>useFetch Usage</h1>
{loading && <p>加载中...</p>}
{error && <p>出错了...</p>}
{response && <p>{response.title}</p>}
</div>
)
}
import { useDebounce, useThrottle } from 'm-hooks'
const debounceCancel = useDebounce(() => {
// callback
}, 2000, [a])
const throttleCancel = useThrottle(() => {
// callback
}, 2000, [a])
useTitle('document title')
import {useField} from 'm-hooks'
const MyComponent = () => {
const { value, bind } = useField('Type Here...')
return (
<div>
input text:
{value}
<input type="text" {...bind} />
</div>
)
}
containerRef
: the ref of the container element.f: () => void
: f is called when click area is inside the contianer element.
containerRef
: the ref of the container element.f: () => void
: f is called when click area is outside the contianer element.
Similar to componentDidMount
in React class component.
f: () => void
: f is called when component did mount.
useDidMount(() => {
console.log('componentDidMount')
})
Close to the componentWillUnmount
in React class component.
f: () => void
: f is called when component will unmount.
useWillUnmount(() => {
console.log('componentWillUnmount')
})
Similar to componentDidUpdate
, it only runs on updates.
f: () => Function | void
: f is called on every updates. LikeuseEffect
, f can return a clean-up function.dependencies?: Array<any>
: Optional array for conditionally firing an effect, same as the second argument passed touseEffect
.
useDidUpdate(() => {
console.log('ComponentDidUpdate')
})
useDidUpdate(() => {
console.log('ComponentDidUpdate')
}, [dep1, dep2])
import { useToggle } from 'm-hooks'
const Toggle = () => {
const { on, toggle, reset } = useToggle(false)
return (
<div>
{String(on)}
<button onClick={toggle}>toggle</button>
<button onClick={reset}>reset</button>
</div>
)
}
import { useHover } from 'm-hooks'
const Hover = () => {
const { hovered, bind } = useHover()
return (
<div>
<div {...bind}>
hovered:
{String(hovered)}
</div>
</div>
)
}
MIT © edwardwang0302
This hook is created using create-react-hook.