useAsync
React 钩子,用于解析 async
函数或返回 promise 的函数。
import {useAsync} from 'react-use';
// Returns a Promise that resolves after one second.
const fn = () => new Promise((resolve) => {
setTimeout(() => {
resolve('RESOLVED');
}, 1000);
});
const Demo = () => {
const state = useAsync(fn);
return (
<div>
{state.loading?
<div>Loading...</div>
: state.error?
<div>Error...</div>
: <div>Value: {state.value}</div>
}
</div>
);
};
useAsync(fn, args?: any[]);
useAsyncFn
React钩子返回状态和async
函数或返回promise的函数的回调。 状态与useAsync
的形状相同。
import {useAsyncFn} from 'react-use';
const Demo = (url) => {
const [state, fetch] = useAsyncFn(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
<div>
{state.loading
? <div>Loading...</div>
: state.error
? <div>Error: {state.error.message}</div>
: state.value && <div>Value: {state.value}</div>
}
<button onClick={() => fetch()}>Start loading</button>
</div>
);
};
useAsyncFn(fn, deps?: any[]);
useAsyncRetry
使用useAsync
和一个额外的retry
方法来轻松重试/刷新异步函数;
import {useAsyncRetry} from 'react-use';
// Returns a Promise that resolves after one second.
const fn = () => new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
reject(new Error('Random error!'));
} else {
resolve('RESOLVED');
}
}, 1000);
});
const Demo = () => {
const state = useAsyncRetry(fn);
return (
<div>
{state.loading?
<div>Loading...</div>
: state.error?
<div>Error...</div>
: <div>Value: {state.value}</div>
}
{!state.loading?
<a href='javascript:void 0' onClick={() => state.retry()}>Retry</a>
: null
}
</div>
);
};
useAsyncRetry(fn, args?: any[]);
useBeforeUnload
React 副作用钩子,当用户试图重新加载或关闭页面时显示浏览器警报。
import {useBeforeUnload} from 'react-use';
const Demo = () => {
const [dirty, toggleDirty] = useToggle(false);
useBeforeUnload(dirty, 'You have unsaved changes, are you sure?');
return (
<div>
{dirty && <p>Try to reload or close tab</p>}
<button onClick={() => toggleDirty()}>{dirty ? 'Disable' : 'Enable'}</button>
</div>
);
};
useCopyToClipboard
将文本复制到用户的剪贴板。
const Demo = () => {
const [text, setText] = React.useState('');
const [state, copyToClipboard] = useCopyToClipboard();
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<button type="button" onClick={() => copyToClipboard(text)}>copy text</button>
{state.error
? <p>Unable to copy value: {state.error.message}</p>
: state.value && <p>Copied {state.value}</p>}
</div>
)
const [text, setText] = React.useState('');
const [copied, copyToClipboard] = useCopyToClipboard(text);
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<button type="button" onClick={copyToClipboard}>copy text</button>
<div>Copied: {copied ? 'Yes' : 'No'}</div>
</div>
)
}
const [state, copyToClipboard] = useCopyToClipboard();
useDebounce
React 钩子,会延迟调用函数,直到上次调用防抖函数以后经过等待毫秒之后。
第三个参数是防抖所依赖的数组值,其方式与 useEffect 中的相同。当其中一个值发生改变,防抖超时将会启动。
import React, { useState } from 'react';
import { useDebounce } from 'react-use';
const Demo = () => {
const [state, setState] = React.useState('Typing stopped');
const [val, setVal] = React.useState('');
useDebounce(
() => {
setState('Typing stopped');
},
2000,
[val]
);
return (
<div>
<input
type="text"
value={val}
placeholder="Debounced input"
onChange={({ currentTarget }) => {
setState('Waiting for typing to stop...');
setVal(currentTarget.value);
}}
/>
<div>{state}</div>
</div>
);
};
useDebouce(fn, ms: number, args: any[]);
useFavicon
React 副作用钩子,用于设置页面图标。
import {useFavicon} from 'react-use';
const Demo = () => {
useFavicon('https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico');
return null;
};
useLocalStorage
React 副作用钩子,用于管理单个 localStorage
键。
import {useLocalStorage} from 'react-use';
const Demo = () => {
const [value, setValue] = useLocalStorage('my-key', 'foo');
return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue('bar')}>bar</button>
<button onClick={() => setValue('baz')}>baz</button>
</div>
);
};
useLocalStorage(key);
useLocalStorage(key, initialValue);
useLocalStorage(key, initialValue, raw);
key
— localStorage
键来管理。initialValue
— 要设置的初始化值,如果localStorage
中的值为空。raw
— boolean,如果设为 true,钩子将不会尝试 JSON 序列化存储的值。useLockBodyScroll
React side-effect hook that locks scrolling on the body element. Useful for modal and other overlay components.
React 锁定在 body 元素上滚动的副作用钩子。适用于模态框和其他覆盖层组件。
import {useLockBodyScroll, useToggle} from 'react-use';
const Demo = () => {
const [locked, toggleLocked] = useToggle(false)
useLockBodyScroll(locked);
return (
<div>
<button onClick={() => toggleLocked()}>
{locked ? 'Unlock' : 'Lock'}
</button>
</div>
);
};
useLockBodyScroll(enabled?: boolean = true);
enabled
— Hook will lock scrolling on the body element if true
, default to true
.useSessionStorage
React 副作用钩子,用于管理单个 sessionStorage
键。
import {useSessionStorage} from 'react-use';
const Demo = () => {
const [value, setValue] = useSessionStorage('my-key', 'foo');
return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue('bar')}>bar</button>
<button onClick={() => setValue('baz')}>baz</button>
</div>
);
};
useSessionStorage(key);
useSessionStorage(key, initialValue);
useSessionStorage(key, initialValue, raw);
key
— sessionStorage
键来管理。initialValue
— 要设置的初始化值,如果sessionStorage
中的值为空。raw
— boolean, 如果设为 true,钩子将不会尝试 JSON 序列化存储的值。useThrottle
and useThrottleFn
用于节流的 React 钩子。
import React, { useState } from 'react';
import { useThrottle, useThrottleFn } from 'react-use';
const Demo = ({value}) => {
const throttledValue = useThrottle(value);
// const throttledValue = useThrottleFn(value => value, 200, [value]);
return (
<>
<div>Value: {value}</div>
<div>Throttled value: {throttledValue}</div>
</>
);
};
useThrottle(value, ms?: number);
useThrottleFn(fn, ms, args);
useTitle
React 副作用钩子,用于设置页面标题。
import {useTitle} from 'react-use';
const Demo = () => {
useTitle('Hello world!');
return null;
};