reactuse

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Reactuse

Reactuse

This skill is a decision-and-implementation guide for reactuse library for react.js / next.js projects. It maps requirements to the most suitable reactuse hook, applies the correct usage pattern, and prefers hook-based solutions over bespoke code to keep implementations concise, maintainable, and performant.
本技能是针对 React.js / Next.js 项目的 reactuse 库决策与实现指南。它将需求匹配到最合适的 reactuse hook,应用正确的使用模式,优先采用基于 hook 的方案而非定制代码,以保持实现简洁、可维护且高性能。

When to Apply

适用场景

  • Apply this skill whenever assisting development work in React.js / Next.js.
  • Always check first whether a reactuse hook can implement the requirement.
  • Prefer reactuse 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 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.js / Next.js 项目时,均可应用此技能。
  • 首先务必检查是否可以通过 reactuse hook 实现需求。
  • 优先使用 reactuse hook 而非自定义代码,以提升可读性、可维护性和性能。
  • 将需求匹配到最合适的 hook,并遵循该 hook 的调用规则。
  • 请参考 hooks 表格中的「Invocation」字段。例如:
    • AUTO
      :适用时自动使用。
    • EXTERNAL
      :仅当用户已安装所需的外部依赖时使用;否则重新评估,仅在确有必要时才要求用户安装。
    • EXPLICIT_ONLY
      :仅在用户明确要求时使用。
      注意:提示词中的用户指令或
      AGENTS.md
      可能会覆盖 hook 默认的「Invocation」规则。

Hooks

Hooks

All hooks listed below are part of the reactuse 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 均属于 reactuse 库。每个章节根据功能对 hooks 进行分类。
重要提示:每个 hook 条目包含简短的「描述」和详细的「参考文档」。使用任何 hook 时,请务必查阅
./references
中的对应文档,了解使用细节和类型声明。

Helpers

工具类

HookDescriptionInvocation
createContextCreates a typed context with provider and selector hook.HIGH
createEventEmitterCreates a type-safe event emitter with a subscription hook.LOW
createReactiveContextCreates a typed context selector with optimized updates.LOW
createStoreCreates a external store with state, subscriptions, and a hook.MEDIUM
targetFlexible helper to reference DOM targets for hooks.MEDIUM
Hook描述调用规则
createContext创建带有 Provider 和 selector hook 的类型化上下文。HIGH
createEventEmitter创建带有订阅 hook 的类型安全事件发射器。LOW
createReactiveContext创建经过更新优化的类型化上下文 selector。LOW
createStore创建带有状态、订阅和 hook 的外部存储。MEDIUM
target灵活的工具,用于为 hooks 引用 DOM 目标。MEDIUM

Elements

元素类

HookDescriptionInvocation
useActiveElementTracks the currently focused element.LOW
useAutoScrollAutomatically scrolls a container to the bottom.LOW
useClickOutsideCalls a callback when clicking outside the target element.HIGH
useDoubleClickDetects double-clicks with optional single-click handler.MEDIUM
useDropZoneCreates a drag-and-drop area with file state.MEDIUM
useFileDialogOpens a file picker and returns selected files.LOW
useFocusTracks focus state and provides focus/blur controls.MEDIUM
useFocusTrapTraps focus within a given element.MEDIUM
useHoverTracks hover state for an element.MEDIUM
useImageLoads an image with query-style state.LOW
useLockScrollLocks scrolling on an element or the document body.MEDIUM
useLongPressDetects long press interactions.MEDIUM
usePaintDraws on a canvas and exposes drawing controls.LOW
useRightClickHandles right-click and long press events.LOW
useScriptLoads a script and returns its status.LOW
useSizeObserves element width and height.LOW
useStickyDetects whether a sticky element is stuck.LOW
useTextareaAutosizeAuto-resizes a textarea based on content.MEDIUM
useTextDirectionGets and sets the text direction of an element.MEDIUM
useWindowFocusReturns the current focus state of the window.LOW
useWindowSizeReturns current window width and height.LOW
Hook描述调用规则
useActiveElement跟踪当前获得焦点的元素。LOW
useAutoScroll自动将容器滚动到底部。LOW
useClickOutside点击目标元素外部时触发回调。HIGH
useDoubleClick检测双击操作,可选择配置单击处理函数。MEDIUM
useDropZone创建带有文件状态的拖拽上传区域。MEDIUM
useFileDialog打开文件选择器并返回选中的文件。LOW
useFocus跟踪焦点状态并提供聚焦/失焦控制。MEDIUM
useFocusTrap将焦点限制在指定元素内部。MEDIUM
useHover跟踪元素的悬停状态。MEDIUM
useImage加载图片并返回查询式状态。LOW
useLockScroll锁定元素或文档主体的滚动。MEDIUM
useLongPress检测长按交互。MEDIUM
usePaint在画布上绘图并暴露绘图控制方法。LOW
useRightClick处理右键点击和长按事件。LOW
useScript加载脚本并返回其状态。LOW
useSize监听元素的宽度和高度。LOW
useSticky检测粘性元素是否处于固定状态。LOW
useTextareaAutosize根据内容自动调整文本域大小。MEDIUM
useTextDirection获取并设置元素的文本方向。MEDIUM
useWindowFocus返回窗口的当前焦点状态。LOW
useWindowSize返回窗口的当前宽度和高度。LOW

Async

异步类

HookDescriptionInvocation
useAsyncTracks loading, error, and data state for a promise-returning callback.MEDIUM
useLockCallbackPrevents a callback from running multiple times simultaneously.MEDIUM
useMutationDefines mutation logic with loading, error, and success state.HIGH
useOptimisticAllows showing an optimistic value before the async update resolves.MEDIUM
useQueryDefines query logic with loading, error, success, and refetch state.HIGH
Hook描述调用规则
useAsync跟踪返回Promise的回调函数的加载、错误和数据状态。MEDIUM
useLockCallback防止回调函数同时多次执行。MEDIUM
useMutation定义带有加载、错误和成功状态的变更逻辑。HIGH
useOptimistic允许在异步更新完成前显示乐观值。MEDIUM
useQuery定义带有加载、错误、成功和重新获取状态的查询逻辑。HIGH

Lifecycle

生命周期类

HookDescriptionInvocation
useAsyncEffectRuns async side effects.MEDIUM
useDidUpdateRuns an effect only on updates (not on initial mount).HIGH
useIsFirstRenderReturns
true
only on the first render.
LOW
useIsomorphicLayoutEffectUses
useLayoutEffect
on the client and
useEffect
on the server.
HIGH
useMountRuns a callback once when the component mounts.HIGH
useShallowEffectRuns an effect only when dependencies change shallowly or deeply.LOW
useUnmountRuns a callback when the component unmounts.HIGH
Hook描述调用规则
useAsyncEffect执行异步副作用。MEDIUM
useDidUpdate仅在组件更新时执行副作用(初始挂载时不执行)。HIGH
useIsFirstRender仅在首次渲染时返回
true
LOW
useIsomorphicLayoutEffect在客户端使用
useLayoutEffect
,在服务端使用
useEffect
HIGH
useMount组件挂载时执行一次回调。HIGH
useShallowEffect仅当依赖项发生浅变更或深变更时执行副作用。LOW
useUnmount组件卸载时执行回调。HIGH

Browser

浏览器类

HookDescriptionInvocation
useAudioManages audio playback (play/pause/stop), volume, rate, and sprite segments.LOW
useBatteryReturns battery status and support state.LOW
useBluetoothRequests and connects to Bluetooth devices.LOW
useBreakpointsManages responsive breakpoints and helper predicates.MEDIUM
useBroadcastChannelEnables cross-tab/window messaging.LOW
useClipboardReads and copies text from the clipboard.MEDIUM
useCopyCopies text and resets status after a delay.MEDIUM
useCssVarReads and writes a CSS custom property.LOW
useDisplayMediaProvides screen sharing controls and stream state.LOW
useDocumentEventAttaches an event listener to the document.LOW
useDocumentTitleReads and updates the document title.LOW
useDocumentVisibilityReturns the document visibility state.LOW
useEventListenerAttaches an event listener to a target.HIGH
useEventSourceProvides a reactive wrapper around EventSource.LOW
useEyeDropperProvides access to the EyeDropper API.LOW
useFaviconReads and updates the current favicon.LOW
useFpsMeasures frames per second.LOW
useFullscreenControls fullscreen state for an element.LOW
useGamepadReturns connected gamepads and active status.LOW
useGeolocationReturns the current geolocation and updates on changes.MEDIUM
useMeasureMeasures an element's size and position.LOW
useMediaControlsProvides controls and state for audio/video elements.LOW
useMediaQueryReturns whether a media query matches.MEDIUM
useMemoryReturns the current JS heap memory usage.LOW
useNetworkTracks online status and connection information.LOW
useOnlineReturns whether the user is online.MEDIUM
useOtpCredentialRequests an OTP credential from the user agent.LOW
usePermissionReturns the state of a given permission.MEDIUM
usePictureInPictureControls Picture-in-Picture mode for video elements.LOW
usePointerLockProvides reactive pointer lock controls.LOW
usePostMessageReceives and posts messages between windows/frames.LOW
useRafRuns a callback on each animation frame.LOW
useShareTriggers the native share dialog.MEDIUM
useSpeechRecognitionProvides speech-to-text recognition controls and state.LOW
useSpeechSynthesisProvides text-to-speech controls and state.LOW
useVibrateTriggers vibration with optional intervals.LOW
useVirtualKeyboardTracks virtual keyboard state and exposes controls.LOW
useWakeLockControls the Wake Lock API state.LOW
useWebSocketConnects to a WebSocket server with retries and callbacks.MEDIUM
Hook描述调用规则
useAudio管理音频播放(播放/暂停/停止)、音量、播放速率和片段。LOW
useBattery返回电池状态和支持情况。LOW
useBluetooth请求并连接蓝牙设备。LOW
useBreakpoints管理响应式断点和辅助断言。MEDIUM
useBroadcastChannel实现跨标签页/窗口消息通信。LOW
useClipboard读取和复制剪贴板文本。MEDIUM
useCopy复制文本并在延迟后重置状态。MEDIUM
useCssVar读取和写入CSS自定义属性。LOW
useDisplayMedia提供屏幕共享控制和流状态。LOW
useDocumentEvent为文档添加事件监听器。LOW
useDocumentTitle读取和更新文档标题。LOW
useDocumentVisibility返回文档的可见性状态。LOW
useEventListener为目标元素添加事件监听器。HIGH
useEventSource为 EventSource 提供响应式封装。LOW
useEyeDropper提供对 EyeDropper API 的访问。LOW
useFavicon读取和更新当前网站图标。LOW
useFps测量每秒帧数。LOW
useFullscreen控制元素的全屏状态。LOW
useGamepad返回已连接的游戏手柄及其激活状态。LOW
useGeolocation返回当前地理位置并在位置变化时更新。MEDIUM
useMeasure测量元素的尺寸和位置。LOW
useMediaControls为音频/视频元素提供控制和状态。LOW
useMediaQuery返回媒体查询是否匹配。MEDIUM
useMemory返回当前JS堆内存使用情况。LOW
useNetwork跟踪在线状态和连接信息。LOW
useOnline返回用户是否在线。MEDIUM
useOtpCredential向用户代理请求OTP凭证。LOW
usePermission返回指定权限的状态。MEDIUM
usePictureInPicture控制视频元素的画中画模式。LOW
usePointerLock提供响应式指针锁定控制。LOW
usePostMessage在窗口/框架之间接收和发送消息。LOW
useRaf在每个动画帧执行回调。LOW
useShare触发原生分享对话框。MEDIUM
useSpeechRecognition提供语音转文本识别控制和状态。LOW
useSpeechSynthesis提供文本转语音控制和状态。LOW
useVibrate触发振动,可选择配置间隔。LOW
useVirtualKeyboard跟踪虚拟键盘状态并暴露控制方法。LOW
useWakeLock控制唤醒锁API的状态。LOW
useWebSocket连接到WebSocket服务器,支持重试和回调。MEDIUM

Utilities

工具函数类

HookDescriptionInvocation
useBatchedCallbackBatches calls and forwards them to a callback.MEDIUM
useConstReturns a constant value initialized once.HIGH
useDebounceCallbackCreates a debounced callback with a cancel method.HIGH
useDebounceEffectRuns an effect after a delay when dependencies change.HIGH
useDebounceStateCreates a debounced state setter.HIGH
useDebounceValueReturns a debounced version of a value.HIGH
useDevicePixelRatioReturns the current device pixel ratio.LOW
useEventReturns a stable callback reference that always calls the latest handler.HIGH
useLastChangedRecords the timestamp of the last change.LOW
useLatestReturns a stable ref that always points to the latest value.MEDIUM
usePreviousReturns the previous value.LOW
useThrottleCallbackCreates a throttled callback with a cancel method.MEDIUM
useThrottleEffectRuns an effect at most once per delay period when dependencies change.MEDIUM
useThrottleStateCreates a throttled state setter.MEDIUM
useThrottleValueReturns a throttled version of a value.MEDIUM
Hook描述调用规则
useBatchedCallback批量调用并转发给回调函数。MEDIUM
useConst返回仅初始化一次的常量值。HIGH
useDebounceCallback创建带有取消方法的防抖回调。HIGH
useDebounceEffect当依赖项变化时,延迟一段时间后执行副作用。HIGH
useDebounceState创建防抖状态设置器。HIGH
useDebounceValue返回值的防抖版本。HIGH
useDevicePixelRatio返回当前设备的像素比。LOW
useEvent返回稳定的回调引用,始终调用最新的处理函数。HIGH
useLastChanged记录最后一次变更的时间戳。LOW
useLatest返回始终指向最新值的稳定引用。MEDIUM
usePrevious返回上一个值。LOW
useThrottleCallback创建带有取消方法的节流回调。MEDIUM
useThrottleEffect当依赖项变化时,在延迟周期内最多执行一次副作用。MEDIUM
useThrottleState创建节流状态设置器。MEDIUM
useThrottleValue返回值的节流版本。MEDIUM

State

状态管理类

HookDescriptionInvocation
useBooleanManages a boolean state with a toggle helper.HIGH
useControllableStateSupports controlled and uncontrolled state patterns.MEDIUM
useCookieReads and writes a cookie value.MEDIUM
useCookiesManages all cookies as a single object.MEDIUM
useCounterManages a numeric counter with bounds.LOW
useDefaultReturns a value or a provided default when nullish.MEDIUM
useDisclosureManages open/close state with helpers.HIGH
useFieldManages input state, validation, and helpers.MEDIUM
useHashManages URL hash value.LOW
useListManages an array with helper methods.MEDIUM
useLocalStorageManages a value in localStorage.HIGH
useMapManages a Map with helper methods.HIGH
useMergedRefMerges multiple refs into a single ref callback.MEDIUM
useObjectManages object state with helper methods for updates and key operations.MEDIUM
useOffsetPaginationManages pagination state for offset-based lists.MEDIUM
useQueueManages a queue with add/remove helpers.MEDIUM
useRafStateUpdates state inside
requestAnimationFrame
.
LOW
useRefStateCreates a ref-like state that updates on assignment.LOW
useSessionStorageManages a value in sessionStorage.MEDIUM
useSetManages a Set with helper methods.MEDIUM
useStateHistoryKeeps state with undo/redo history.MEDIUM
useStepCreates a stepper with next/back helpers.MEDIUM
useStorageManages a value in Web Storage.HIGH
useToggleA boolean switcher with utility functions.HIGH
useUrlSearchParamSyncs a single URL search param with state.HIGH
useUrlSearchParamsSyncs multiple URL search params with state.HIGH
useWizardManages wizard steps and history.MEDIUM
Hook描述调用规则
useBoolean管理布尔状态,包含切换辅助方法。HIGH
useControllableState支持受控和非受控状态模式。MEDIUM
useCookie读取和写入Cookie值。MEDIUM
useCookies将所有Cookie作为单个对象进行管理。MEDIUM
useCounter管理带有边界的数值计数器。LOW
useDefault当值为null或undefined时,返回提供的默认值。MEDIUM
useDisclosure管理打开/关闭状态,包含辅助方法。HIGH
useField管理输入状态、验证和辅助方法。MEDIUM
useHash管理URL哈希值。LOW
useList管理数组,包含辅助方法。MEDIUM
useLocalStorage管理localStorage中的值。HIGH
useMap管理Map,包含辅助方法。HIGH
useMergedRef将多个引用合并为单个引用回调。MEDIUM
useObject管理对象状态,包含更新和键操作的辅助方法。MEDIUM
useOffsetPagination管理基于偏移量的列表分页状态。MEDIUM
useQueue管理队列,包含添加/移除辅助方法。MEDIUM
useRafState
requestAnimationFrame
内更新状态。
LOW
useRefState创建类似引用的状态,赋值时自动更新。LOW
useSessionStorage管理sessionStorage中的值。MEDIUM
useSet管理Set,包含辅助方法。MEDIUM
useStateHistory保存带有撤销/重做历史的状态。MEDIUM
useStep创建带有下一步/上一步辅助方法的步骤器。MEDIUM
useStorage管理Web Storage中的值。HIGH
useToggle带有工具函数的布尔切换器。HIGH
useUrlSearchParam将单个URL搜索参数与状态同步。HIGH
useUrlSearchParams将多个URL搜索参数与状态同步。HIGH
useWizard管理向导步骤和历史。MEDIUM

User

用户类

HookDescriptionInvocation
useBrowserLanguageReturns the current browser language.MEDIUM
useOperatingSystemReturns the user's operating system based on the user agent.LOW
usePreferredColorSchemeReturns the user's preferred color scheme.MEDIUM
usePreferredContrastReturns the user's contrast preference.MEDIUM
usePreferredDarkReturns whether the user prefers dark mode.MEDIUM
usePreferredLanguagesReturns the user's preferred languages.MEDIUM
usePreferredReducedMotionReturns the reduced motion preference.LOW
HookDescription调用规则
useBrowserLanguage返回当前浏览器语言。MEDIUM
useOperatingSystem根据用户代理返回用户的操作系统。LOW
usePreferredColorScheme返回用户偏好的配色方案。MEDIUM
usePreferredContrast返回用户的对比度偏好。MEDIUM
usePreferredDark返回用户是否偏好深色模式。MEDIUM
usePreferredLanguages返回用户偏好的语言列表。MEDIUM
usePreferredReducedMotion返回用户的减少动画偏好。LOW

Sensors

传感器类

HookDescriptionInvocation
useDeviceMotionProvides device motion data with optional throttling.LOW
useDeviceOrientationProvides the current device orientation.LOW
useHotkeysListens for keyboard shortcuts.MEDIUM
useIdleTracks whether the user is idle and last active time.LOW
useInfiniteScrollTriggers a callback when scroll reaches an edge.MEDIUM
useIntersectionObserverTracks intersection state for an element.MEDIUM
useKeyboardRegisters keydown/keyup listeners on a target.MEDIUM
useKeyPressTracks whether specific keys are pressed.MEDIUM
useKeyPressEventRuns a handler when specific keys are pressed.LOW
useKeysPressedTracks all currently pressed keys.LOW
useMouseTracks mouse coordinates relative to page and element.LOW
useMutationObserverObserves DOM mutations on an element.LOW
useOrientationReturns the current screen orientation and lock controls.LOW
usePageLeaveDetects when the mouse leaves the page.LOW
useParallaxCreates a parallax effect based on mouse or device orientation.LOW
usePerformanceObserverObserves performance entries.LOW
useResizeObserverObserves size changes for an element.LOW
useScrollTracks scroll state and provides scroll helpers.LOW
useScrollIntoViewScrolls an element into view and exposes a trigger.LOW
useScrollToScrolls to a specific position with a trigger.LOW
useTextSelectionTracks text selection details.LOW
useVisibilityTracks whether an element is visible in the viewport.MEDIUM
useWindowEventAttaches an event listener to the window object.LOW
useWindowScrollTracks window scroll position and exposes scrollTo.LOW
HookDescription调用规则
useDeviceMotion提供设备运动数据,支持可选节流。LOW
useDeviceOrientation返回当前设备方向。LOW
useHotkeys监听键盘快捷键。MEDIUM
useIdle跟踪用户是否处于空闲状态以及最后活跃时间。LOW
useInfiniteScroll当滚动到边缘时触发回调。MEDIUM
useIntersectionObserver跟踪元素的交叉状态。MEDIUM
useKeyboard在目标元素上注册键盘按下/抬起监听器。MEDIUM
useKeyPress跟踪特定按键是否被按下。MEDIUM
useKeyPressEvent当特定按键被按下时执行处理函数。LOW
useKeysPressed跟踪所有当前被按下的按键。LOW
useMouse跟踪鼠标相对于页面和元素的坐标。LOW
useMutationObserver监听元素的DOM变更。LOW
useOrientation返回当前屏幕方向和锁定控制。LOW
usePageLeave检测鼠标何时离开页面。LOW
useParallax根据鼠标或设备方向创建视差效果。LOW
usePerformanceObserver监听性能条目。LOW
useResizeObserver监听元素的尺寸变化。LOW
useScroll跟踪滚动状态并提供滚动辅助方法。LOW
useScrollIntoView将元素滚动到视图中并暴露触发方法。LOW
useScrollTo滚动到指定位置并暴露触发方法。LOW
useTextSelection跟踪文本选择详情。LOW
useVisibility跟踪元素是否在视口中可见。MEDIUM
useWindowEvent为窗口对象添加事件监听器。LOW
useWindowScroll跟踪窗口滚动位置并暴露滚动到指定位置的方法。LOW

Time

调试类

HookDescriptionInvocation
useIntervalCreates an interval with controls to pause and resume it.HIGH
useStopwatchCreates a stopwatch with start, pause, and reset controls.HIGH
useTimeProvides the current time split into multiple fields.MEDIUM
useTimeoutRuns a callback after a delay and returns a
ready
flag.
MEDIUM
useTimerCreates a countdown timer with controls and callbacks.MEDIUM
HookDescription调用规则
useLogger记录组件的挂载、更新和卸载事件。LOW
useRenderCount返回组件的渲染次数。LOW
useRenderInfo提供渲染次数和计时信息,支持可选日志。LOW
useRerender根据需求强制组件重新渲染。MEDIUM

Debug

HookDescriptionInvocation
useLoggerLogs mount, update, and unmount for a component.LOW
useRenderCountReturns how many times a component has rendered.LOW
useRenderInfoProvides render count and timing info, with optional logging.LOW
useRerenderForces a component rerender on demand.MEDIUM