react-use-hooks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React-Use Hooks

React-Use Hooks

This skill is a decision-and-implementation guide for react-use hooks in React projects. It maps requirements to the most suitable react-use hook, applies the correct usage pattern, and prefers hook-based solutions over bespoke code to keep implementations concise, maintainable, and performant.
本指南是React项目中react-use hooks的决策与实现参考,它将需求映射到最合适的react-use hook,采用正确的使用模式,优先选择基于hook的解决方案而非自定义代码,以保持实现的简洁性、可维护性和性能。

When to Apply

适用场景

  • Apply this skill whenever assisting user development work in React.
  • Always check first whether a react-use hook can implement the requirement.
  • Prefer react-use hooks over custom code to improve readability, maintainability, and performance.
  • Map requirements to the most appropriate hook and follow the hook's invocation rule.
  • Please refer to the
    Invocation
    field in the below hooks table. For example:
    • AUTO
      : Use automatically when applicable.
    • EXTERNAL
      : Use only if the user already installed the required external dependency; otherwise reconsider, and ask to install only if truly needed.
    • EXPLICIT_ONLY
      : Use only when explicitly requested by the user.
    NOTE User instructions in the prompt or
    AGENTS.md
    may override a hook's default
    Invocation
    rule.
  • 每当协助用户进行React开发工作时,都可以运用本指南。
  • 首先始终要检查是否可以通过react-use hook来实现需求。
  • 优先使用react-use hooks而非自定义代码,以提升可读性、可维护性和性能。
  • 将需求映射到最合适的hook,并遵循该hook的调用规则。
  • 请参考下方hooks表格中的
    Invocation
    字段。例如:
    • AUTO
      : 适用时自动使用。
    • EXTERNAL
      : 仅当用户已安装所需的外部依赖时使用;否则重新考虑,仅在确实需要时才要求用户安装。
    • EXPLICIT_ONLY
      : 仅在用户明确要求时使用。
    注意:提示中的用户指令或
    AGENTS.md
    可能会覆盖hook的默认
    Invocation
    规则。

Hooks

Hooks

All hooks listed below are part of the react-use library, each section categorizes hooks based on their functionality.
IMPORTANT: Each hook entry includes a short
Description
and a detailed
Reference
. When using any hook, always consult the corresponding document in
./references
for Usage details and Type Declarations.
以下列出的所有hooks均属于react-use库,各章节根据功能对hooks进行分类。
重要提示:每个hook条目都包含简短的
Description
和详细的
Reference
。使用任何hook时,请务必查阅
./references
中的对应文档,了解使用细节和类型声明。

Sensors

传感器类

HookDescriptionInvocation
createBreakpoint
laptopL: 1440, laptop: 1024, tablet: 768AUTO
useBattery
React sensor hook that tracks battery status.AUTO
useGeolocation
React sensor hook that tracks user's geographic location. This hook accepts [position options](httpsAUTO
useHash
React sensor hook that tracks browser's location hash.AUTO
useHover
React UI sensor hooks that track if some element is being hoveredAUTO
useHoverDirty
Tracks mouse hover state using a ref (more direct than useHover).AUTO
useIdle
React sensor hook that tracks if user on the page is idle.AUTO
useIntersection
React sensor hook that tracks the changes in the intersection of a target element with an ancestor eAUTO
useKey
React UI sensor hook that executes a
handler
when a keyboard key is used.
AUTO
useKeyboardJs
React UI sensor hook that detects complex key combos like detecting whenEXTERNAL
useKeyPress
React UI sensor hook that detects when the user is pressing a specificAUTO
useKeyPressEvent
This hook fires
keydown
and
keyup
callbacks, similar to how
useKey
AUTO
useLocation
React sensor hook that tracks brower's location.AUTO
useLongPress
React sensor hook that fires a callback after long pressing.AUTO
useMeasure
React sensor hook that tracks dimensions of an HTML element using the [Resize Observer API](https://AUTO
useMedia
React sensor hook that tracks state of a CSS media query.AUTO
useMediaDevices
React sensor hook that tracks connected hardware devices.AUTO
useMotion
React sensor hook that uses device's acceleration sensor to track its motions.AUTO
useMouse
React sensor hooks that re-render on mouse position changes.
useMouse
simply tracks
AUTO
useMouseHovered
Extended mouse tracking with options for bounded coordinates and hover-only tracking.AUTO
useMouseWheel
React Hook to get deltaY of mouse scrolled in window.AUTO
useNetworkState
Tracks the state of browser's network connection.AUTO
useOrientation
React sensor hook that tracks screen orientation of user's device.AUTO
usePageLeave
React sensor hook that fires a callback when mouse leaves the page.AUTO
usePinchZoom
React sensor hook that tracks the changes in pointer touch events and detects value of pinch differeAUTO
useScratch
React sensor hook that tracks state of mouse "scrubs" (or "scratches").AUTO
useScroll
React sensor hook that re-renders when the scroll position in a DOM element changes.AUTO
useScrollbarWidth
Hook that will return current browser's scrollbar width.AUTO
useScrolling
React sensor hook that keeps track of whether the user is scrolling or not.AUTO
useSearchParam
React sensor hook that tracks browser's location search param.AUTO
useSize
React sensor hook that tracks size of an HTML element.AUTO
useStartTyping
React sensor hook that fires a callback when user starts typing. Can be usedAUTO
useWindowScroll
React sensor hook that re-renders on window scroll.AUTO
useWindowSize
React sensor hook that tracks dimensions of the browser window.AUTO
HookDescriptionInvocation
createBreakpoint
laptopL: 1440, laptop: 1024, tablet: 768AUTO
useBattery
跟踪电池状态的React传感器hook。AUTO
useGeolocation
跟踪用户地理位置的React传感器hook。该hook接受[定位选项](httpsAUTO
useHash
跟踪浏览器地址栏哈希值的React传感器hook。AUTO
useHover
跟踪元素是否被悬停的React UI传感器hookAUTO
useHoverDirty
使用ref跟踪鼠标悬停状态(比useHover更直接)。AUTO
useIdle
跟踪页面用户是否处于空闲状态的React传感器hook。AUTO
useIntersection
跟踪目标元素与祖先元素交叉变化的React传感器hookAUTO
useKey
当按下键盘按键时执行
handler
的React UI传感器hook。
AUTO
useKeyboardJs
检测复杂组合键的React UI传感器hook,比如检测当EXTERNAL
useKeyPress
检测用户是否正在按下特定按键的React UI传感器hookAUTO
useKeyPressEvent
该hook触发
keydown
keyup
回调,类似于
useKey
AUTO
useLocation
跟踪浏览器地址的React传感器hook。AUTO
useLongPress
长按后触发回调的React传感器hook。AUTO
useMeasure
使用[Resize Observer API](https://跟踪HTML元素尺寸的React传感器hook。AUTO
useMedia
跟踪CSS媒体查询状态的React传感器hook。AUTO
useMediaDevices
跟踪已连接硬件设备的React传感器hook。AUTO
useMotion
使用设备加速度传感器跟踪运动状态的React传感器hook。AUTO
useMouse
鼠标位置变化时重新渲染的React传感器hook。
useMouse
仅简单跟踪
AUTO
useMouseHovered
扩展鼠标跟踪,支持边界坐标和仅悬停跟踪选项。AUTO
useMouseWheel
获取窗口中鼠标滚动deltaY值的React Hook。AUTO
useNetworkState
跟踪浏览器网络连接状态。AUTO
useOrientation
跟踪用户设备屏幕方向的React传感器hook。AUTO
usePageLeave
当鼠标离开页面时触发回调的React传感器hook。AUTO
usePinchZoom
跟踪指针触摸事件变化并检测捏合缩放值的React传感器hookAUTO
useScratch
跟踪鼠标“刮擦”状态的React传感器hook。AUTO
useScroll
DOM元素滚动位置变化时重新渲染的React传感器hook。AUTO
useScrollbarWidth
返回当前浏览器滚动条宽度的hook。AUTO
useScrolling
跟踪用户是否正在滚动的React传感器hook。AUTO
useSearchParam
跟踪浏览器地址栏查询参数的React传感器hook。AUTO
useSize
跟踪HTML元素尺寸的React传感器hook。AUTO
useStartTyping
用户开始输入时触发回调的React传感器hook,可用于AUTO
useWindowScroll
窗口滚动时重新渲染的React传感器hook。AUTO
useWindowSize
跟踪浏览器窗口尺寸的React传感器hook。AUTO

UI

UI类

HookDescriptionInvocation
useAudio
Creates
<audio>
element, tracks its state and exposes playback controls.
AUTO
useClickAway
React UI hook that triggers a callback when userAUTO
useCss
React UI hook that changes [CSS dynamically][gen-5]. Works like "virtual CSS" —AUTO
useDrop
Triggers on file, link drop and copy-paste.AUTO
useFullscreen
Display an element full-screen, optional fallback for fullscreen video on iOS.AUTO
useSlider
React UI hook that provides slide behavior over any HTML element. Supports both mouse and touch evenAUTO
useSpeech
React UI hook that synthesizes human voice that speaks a given string.AUTO
useVibrate
React UI hook to provide physical feedback with device vibration hardware using the [Vibration API](AUTO
useVideo
Creates
<video>
element, tracks its state and exposes playback controls.
AUTO
HookDescriptionInvocation
useAudio
创建
<audio>
元素,跟踪其状态并暴露播放控制方法。
AUTO
useClickAway
用户点击元素外部时触发回调的React UI hookAUTO
useCss
动态修改[CSS][gen-5]的React UI hook。类似于“虚拟CSS”——AUTO
useDrop
触发文件、链接拖放和粘贴事件。AUTO
useFullscreen
将元素显示为全屏,支持iOS上全屏视频的备选方案。AUTO
useSlider
为任意HTML元素提供滑动行为的React UI hook,支持鼠标和触摸事件AUTO
useSpeech
将给定字符串合成为人声的React UI hook。AUTO
useVibrate
使用[Vibration API]实现设备振动物理反馈的React UI hookAUTO
useVideo
创建
<video>
元素,跟踪其状态并暴露播放控制方法。
AUTO

Animations

动画类

HookDescriptionInvocation
useHarmonicIntervalFn
Same as
useInterval
hook, but triggers all effects with the same delay
AUTO
useInterval
A declarative interval hook based on [Dan Abramov's article on overreacted.io](https://overreacted.iAUTO
useRaf
React animation hook that forces component to re-render on each
requestAnimationFrame
,
AUTO
useSpring
React animation hook that updates a single numeric value over time accordingEXTERNAL
useTimeout
Re-renders the component after a specified number of milliseconds.AUTO
useTimeoutFn
Calls given function after specified amount of milliseconds.AUTO
useTween
React animation hook that tweens a number between 0 and 1.AUTO
useUpdate
React utility hook that returns a function that forces componentAUTO
HookDescriptionInvocation
useHarmonicIntervalFn
useInterval
hook功能相同,但所有效果都以相同延迟触发
AUTO
useInterval
基于Dan Abramov在overreacted.io上的文章实现的声明式interval hookAUTO
useRaf
强制组件在每个
requestAnimationFrame
时重新渲染的React动画hook,
AUTO
useSpring
随时间更新单个数值的React动画hook,遵循EXTERNAL
useTimeout
指定毫秒数后重新渲染组件。AUTO
useTimeoutFn
指定毫秒数后调用给定函数。AUTO
useTween
在0到1之间补间数值的React动画hook。AUTO
useUpdate
返回强制组件重新渲染函数的React工具hookAUTO

Side-Effects

副作用类

HookDescriptionInvocation
useAsync
React hook that resolves an
async
function or a function that returns
AUTO
useAsyncFn
React hook that returns state and a callback for an
async
function or a
AUTO
useAsyncRetry
Uses
useAsync
with an additional
retry
method to easily retry/refresh the async function;
AUTO
useBeforeUnload
React side-effect hook that shows browser alert when user try to reload or close the page.AUTO
useCookie
React hook that returns the current value of a
cookie
, a callback to update the
cookie
AUTO
useCopyToClipboard
Copy text to a user's clipboard.AUTO
useDebounce
React hook that delays invoking a function until after wait milliseconds have elapsed since the lastAUTO
useError
React side-effect hook that returns an error dispatcher.AUTO
useFavicon
React side-effect hook sets the favicon of the page.AUTO
useLocalStorage
React side-effect hook that manages a single
localStorage
key.
AUTO
useLockBodyScroll
React side-effect hook that locks scrolling on the body element. Useful for modal and other overlayAUTO
usePermission
React side-effect hook to query permission status of browser APIs.AUTO
useRafLoop
This hook call given function within the RAF loop without re-rendering parent component.AUTO
useSessionStorage
React side-effect hook that manages a single
sessionStorage
key.
AUTO
useThrottle
React hooks that throttle.AUTO
useThrottleFn
React hook that invokes a function and then delays subsequent function calls until after wait millisAUTO
useTitle
React side-effect hook that sets title of the page.AUTO
HookDescriptionInvocation
useAsync
解析
async
函数或返回值为Promise的函数的React hook
AUTO
useAsyncFn
返回状态和
async
函数回调的React hook
AUTO
useAsyncRetry
基于
useAsync
实现,额外提供
retry
方法以轻松重试/刷新异步函数;
AUTO
useBeforeUnload
用户尝试刷新或关闭页面时显示浏览器提示的React副作用hook。AUTO
useCookie
返回
cookie
当前值及更新
cookie
回调的React hook
AUTO
useCopyToClipboard
将文本复制到用户剪贴板。AUTO
useDebounce
延迟调用函数,直到距离上次调用已过指定毫秒数的React hookAUTO
useError
返回错误调度器的React副作用hook。AUTO
useFavicon
设置页面图标的React副作用hook。AUTO
useLocalStorage
管理单个
localStorage
键的React副作用hook。
AUTO
useLockBodyScroll
锁定body元素滚动的React副作用hook,适用于模态框和其他覆盖层AUTO
usePermission
查询浏览器API权限状态的React副作用hook。AUTO
useRafLoop
在RAF循环中调用给定函数而不重新渲染父组件的hook。AUTO
useSessionStorage
管理单个
sessionStorage
键的React副作用hook。
AUTO
useThrottle
实现节流功能的React hook。AUTO
useThrottleFn
调用函数后延迟后续调用,直到距离上次调用已过指定毫秒数的React hookAUTO
useTitle
设置页面标题的React副作用hook。AUTO

Lifecycles

生命周期类

HookDescriptionInvocation
useCustomCompareEffect
A modified useEffect hook that accepts a comparator which is used for comparison on dependencies insAUTO
useDeepCompareEffect
A modified useEffect hook that is using deep comparison on its dependencies instead of reference equAUTO
useEffectOnce
React lifecycle hook that runs an effect only once.AUTO
useEvent
React sensor hook that subscribes a
handler
to events.
AUTO
useIsomorphicLayoutEffect
useLayoutEffect
that does not show warning when server-side rendering, see [Alex Reardon's article
AUTO
useLifecycles
React lifecycle hook that call
mount
and
unmount
callbacks, when
AUTO
useLogger
React lifecycle hook that console logs parameters as component transitions through lifecycles.AUTO
useMount
React lifecycle hook that calls a function after the component is mounted. Use
useLifecycles
if yo
AUTO
useMountedState
> NOTE!: despite having
State
in its name this hook does not cause component re-render.
AUTO
usePromise
React Lifecycle hook that returns a helper function for wrapping promises.AUTO
useShallowCompareEffect
A modified useEffect hook that is using shallow comparison on each of its dependencies instead of reAUTO
useUnmount
React lifecycle hook that calls a function when the component will unmount. Use
useLifecycles
if y
AUTO
useUnmountPromise
A life-cycle hook that provides a higher order promise that does not resolve if component un-mounts.AUTO
useUpdateEffect
React effect hook that ignores the first invocation (e.g. on mount). The signature is exactly the saAUTO
HookDescriptionInvocation
useCustomCompareEffect
改良版useEffect hook,接受比较器用于依赖项比较AUTO
useDeepCompareEffect
改良版useEffect hook,对依赖项进行深度比较而非引用比较AUTO
useEffectOnce
仅运行一次effect的React生命周期hook。AUTO
useEvent
订阅
handler
到事件的React传感器hook。
AUTO
useIsomorphicLayoutEffect
服务端渲染时不显示警告的
useLayoutEffect
,详见Alex Reardon的文章
AUTO
useLifecycles
组件挂载和卸载时调用
mount
unmount
回调的React生命周期hook
AUTO
useLogger
组件生命周期转换时在控制台记录参数的React生命周期hook。AUTO
useMount
组件挂载后调用函数的React生命周期hook。如果需要同时处理挂载和卸载,请使用
useLifecycles
AUTO
useMountedState
> 注意!: 尽管名称中包含
State
,但该hook不会导致组件重新渲染
AUTO
usePromise
返回包装Promise辅助函数的React生命周期hook。AUTO
useShallowCompareEffect
改良版useEffect hook,对每个依赖项进行浅比较而非引用比较AUTO
useUnmount
组件即将卸载时调用函数的React生命周期hook。如果需要同时处理挂载和卸载,请使用
useLifecycles
AUTO
useUnmountPromise
提供高阶Promise的生命周期hook,组件卸载时Promise不会 resolve。AUTO
useUpdateEffect
忽略首次调用(如挂载时)的React effect hook,签名与标准useEffect完全相同AUTO

State

状态管理类

HookDescriptionInvocation
createGlobalState
A React hook that creates a globally shared state.AUTO
createMemo
Hook factory, receives a function to be memoized, returns a memoized React hook,AUTO
createReducer
Factory for reducer hooks with custom middleware with an identical API as [React's
useReducer
](htt
AUTO
createReducerContext
Factory for react context hooks that will behave just like [React's
useReducer
](https://reactjs.or
AUTO
createStateContext
Factory for react context hooks that will behave just like [React's
useState
](https://reactjs.org/
AUTO
useBoolean
Alias for
useToggle
. Boolean state hook with a toggle function.
AUTO
useCounter
React state hook that tracks a numeric value.AUTO
useDefault
React state hook that returns the default value when state is null or undefined.AUTO
useFirstMountState
Returns
true
if component is just mounted (on first render) and
false
otherwise.
AUTO
useGetSet
React state hook that returns state getter function instead ofAUTO
useGetSetState
A mix of
useGetSet
and
useGetSetState
.
AUTO
useLatest
React state hook that returns the latest state as described in the [React hooks FAQ](https://reactjsAUTO
useList
Tracks an array and provides methods to modify it.AUTO
useMap
React state hook that tracks a value of an object.AUTO
useMediatedState
A lot like the standard
useState
, but with mediation process.
AUTO
useMethods
React hook that simplifies the
useReducer
implementation.
AUTO
useMultiStateValidator
Each time any of given states changes - validator function is invoked.AUTO
useNumber
Alias for
useCounter
. Numeric counter state with utility functions.
AUTO
useObservable
React state hook that tracks the latest value of an
Observable
.
EXTERNAL
usePrevious
React state hook that returns the previous state as described in the [React hooks FAQ](https://reactAUTO
usePreviousDistinct
Just like
usePrevious
but it will only update once the value actually changes. This is important w
AUTO
useQueue
React state hook implements simple FIFO queue.AUTO
useRafState
React state hook that only updates state in the callback of [
requestAnimationFrame
](https://develo
AUTO
useRendersCount
Tracks component's renders count including the first render.AUTO
useSet
React state hook that tracks a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/ReferenAUTO
useSetState
React state hook that creates
setState
method which works similar to how
AUTO
useStateList
Provides handles for circular iteration over states list.AUTO
useStateValidator
Each time given state changes - validator function is invoked.AUTO
useStateWithHistory
Stores defined amount of previous state values and provides handles to travel through them.AUTO
useToggle
React state hook that tracks value of a boolean.AUTO
HookDescriptionInvocation
createGlobalState
创建全局共享状态的React hook。AUTO
createMemo
Hook工厂,接收待 memoize 的函数,返回memoized的React hookAUTO
createReducer
带自定义中间件的reducer hook工厂,API与React的
useReducer
完全一致
AUTO
createReducerContext
React上下文hook工厂,行为与React的
useReducer
完全一致
AUTO
createStateContext
React上下文hook工厂,行为与React的
useState
完全一致
AUTO
useBoolean
useToggle
的别名,带切换函数的布尔状态hook。
AUTO
useCounter
跟踪数值的React状态hook。AUTO
useDefault
状态为null或undefined时返回默认值的React状态hook。AUTO
useFirstMountState
组件刚挂载(首次渲染)时返回
true
,否则返回
false
AUTO
useGetSet
返回状态获取函数而非直接返回状态的React状态hookAUTO
useGetSetState
useGetSet
useState
的混合版。
AUTO
useLatest
返回最新状态的React状态hook,详见[React hooks FAQ](https://reactjsAUTO
useList
跟踪数组并提供修改方法。AUTO
useMap
跟踪对象值的React状态hook。AUTO
useMediatedState
与标准
useState
类似,但带有中间处理过程。
AUTO
useMethods
简化
useReducer
实现的React hook。
AUTO
useMultiStateValidator
任意给定状态变化时,调用验证函数。AUTO
useNumber
useCounter
的别名,带工具函数的数值计数器状态hook。
AUTO
useObservable
跟踪
Observable
最新值的React状态hook。
EXTERNAL
usePrevious
返回上一次状态的React状态hook,详见[React hooks FAQ](https://reactAUTO
usePreviousDistinct
usePrevious
类似,但仅在值实际变化时才更新。这在处理
AUTO
useQueue
实现简单FIFO队列的React状态hook。AUTO
useRafState
仅在
requestAnimationFrame
回调中更新状态的React状态hook
AUTO
useRendersCount
跟踪组件渲染次数(包括首次渲染)。AUTO
useSet
跟踪[Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referen的React状态hookAUTO
useSetState
创建类似类组件
setState
方法的React状态hook
AUTO
useStateList
提供状态列表循环迭代的处理方法。AUTO
useStateValidator
给定状态变化时,调用验证函数。AUTO
useStateWithHistory
存储指定数量的历史状态值,并提供回溯方法。AUTO
useToggle
跟踪布尔值的React状态hook。AUTO

Miscellaneous

其他类

HookDescriptionInvocation
useEnsuredForwardedRef
React hook to use a ForwardedRef safely.AUTO
HookDescriptionInvocation
useEnsuredForwardedRef
安全使用ForwardedRef的React hook。AUTO