react-use

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

react-use

react-use

The skill is based on react-use v17.6.0, generated at 2026-01-29.
react-use is a collection of essential React Hooks that provide ready-to-use functionality for common patterns in React applications. It includes hooks for sensors, UI interactions, animations, side-effects, lifecycle management, and state management.
本技能基于react-use v17.6.0版本,生成于2026年1月29日。
react-use是一个包含各类必备React Hooks的集合,可为React应用中的常见模式提供即用型功能。它涵盖了传感器、UI交互、动画、副作用、生命周期管理和状态管理相关的钩子。

Core References

核心参考

TopicDescriptionReference
UsageImport patterns and tree-shaking recommendationscore-usage
主题描述参考链接
使用方法导入模式及Tree-shaking建议core-usage

Sensors

传感器类钩子

Sensor hooks listen to changes in browser APIs and device interfaces, forcing components to re-render with updated state.
TopicDescriptionReference
useBatteryTracks device battery statussensors-battery
useGeolocationTracks geo location state of user's devicesensors-geolocation
useHoverTracks mouse hover state of an elementsensors-hover
useHashTracks location hash valuesensors-hash
useIdleTracks whether user is being inactivesensors-idle
useIntersectionTracks an HTML element's intersectionsensors-intersection
useKeyTracks key pressessensors-key
useKeyPressTracks key press statesensors-key-press
useKeyPressEventHandles key press eventssensors-key-press-event
useKeyboardJsTracks keyboard key combinationssensors-keyboard-js
useLocationTracks page navigation bar location statesensors-location
useSearchParamTracks URL search parameterssensors-search-param
useLongPressTracks long press gesturesensors-long-press
useMediaTracks state of a CSS media querysensors-media
useMediaDevicesTracks state of connected hardware devicessensors-media-devices
useMotionTracks state of device's motion sensorsensors-motion
useMouseTracks state of mouse positionsensors-mouse
useMouseWheelTracks deltaY of scrolled mouse wheelsensors-mouse-wheel
useNetworkStateTracks browser's network connection statesensors-network-state
useOrientationTracks device's screen orientationsensors-orientation
usePageLeaveTriggers when mouse leaves page boundariessensors-page-leave
useScratchTracks mouse click-and-scrub statesensors-scratch
useScrollTracks an HTML element's scroll positionsensors-scroll
useScrollingTracks whether HTML element is scrollingsensors-scrolling
useStartTypingDetects when user starts typingsensors-start-typing
useWindowScrollTracks Window scroll positionsensors-window-scroll
useWindowSizeTracks Window dimensionssensors-window-size
useMeasureTracks an HTML element's dimensionssensors-measure
useSizeTracks element sizesensors-size
createBreakpointTracks innerWidth with breakpointssensors-breakpoint
useScrollbarWidthDetects browser's native scrollbars widthsensors-scrollbar-width
usePinchZoomTracks pointer events to detect pinch zoomsensors-pinch-zoom
传感器类钩子监听浏览器API和设备接口的变化,促使组件使用更新后的状态重新渲染。
主题描述参考链接
useBattery跟踪设备电池状态sensors-battery
useGeolocation跟踪用户设备的地理位置状态sensors-geolocation
useHover跟踪元素的鼠标悬停状态sensors-hover
useHash跟踪地址栏hash值sensors-hash
useIdle跟踪用户是否处于非活跃状态sensors-idle
useIntersection跟踪HTML元素的交叉状态sensors-intersection
useKey跟踪按键操作sensors-key
useKeyPress跟踪按键按下的状态sensors-key-press
useKeyPressEvent处理按键按下事件sensors-key-press-event
useKeyboardJs跟踪键盘组合键sensors-keyboard-js
useLocation跟踪导航栏的位置状态sensors-location
useSearchParam跟踪URL搜索参数sensors-search-param
useLongPress跟踪长按手势sensors-long-press
useMedia跟踪CSS媒体查询的状态sensors-media
useMediaDevices跟踪已连接硬件设备的状态sensors-media-devices
useMotion跟踪设备运动传感器的状态sensors-motion
useMouse跟踪鼠标位置状态sensors-mouse
useMouseWheel跟踪鼠标滚轮滚动的deltaY值sensors-mouse-wheel
useNetworkState跟踪浏览器的网络连接状态sensors-network-state
useOrientation跟踪设备的屏幕方向sensors-orientation
usePageLeave当鼠标离开页面边界时触发sensors-page-leave
useScratch跟踪鼠标点击并拖动的状态sensors-scratch
useScroll跟踪HTML元素的滚动位置sensors-scroll
useScrolling跟踪HTML元素是否正在滚动sensors-scrolling
useStartTyping检测用户开始输入的操作sensors-start-typing
useWindowScroll跟踪浏览器窗口的滚动位置sensors-window-scroll
useWindowSize跟踪浏览器窗口的尺寸sensors-window-size
useMeasure跟踪HTML元素的尺寸sensors-measure
useSize跟踪元素尺寸sensors-size
createBreakpoint结合断点跟踪窗口宽度sensors-breakpoint
useScrollbarWidth检测浏览器原生滚动条的宽度sensors-scrollbar-width
usePinchZoom跟踪指针事件以检测捏合缩放操作sensors-pinch-zoom

UI

UI类钩子

UI hooks allow you to control and subscribe to state changes of UI elements.
TopicDescriptionReference
useAudioPlays audio and exposes its controlsui-audio
useClickAwayTriggers callback when user clicks outside target areaui-click-away
useCssDynamically adjusts CSSui-css
useDropTracks file, link and copy-paste dropsui-drop
useFullscreenDisplay an element or video full-screenui-fullscreen
useSliderProvides slide behavior over any HTML elementui-slider
useSpeechSynthesizes speech from a text stringui-speech
useVibrateProvides physical feedback using Vibration APIui-vibrate
useVideoPlays video, tracks its state, and exposes playback controlsui-video
UI类钩子允许你控制并订阅UI元素的状态变化。
主题描述参考链接
useAudio播放音频并暴露控制方法ui-audio
useClickAway当用户点击目标区域外时触发回调ui-click-away
useCss动态调整CSS样式ui-css
useDrop跟踪文件、链接和粘贴内容的拖放操作ui-drop
useFullscreen将元素或视频全屏显示ui-fullscreen
useSlider为任意HTML元素提供滑动行为ui-slider
useSpeech将文本字符串合成为语音ui-speech
useVibrate使用振动API提供物理反馈ui-vibrate
useVideo播放视频、跟踪其状态并暴露播放控制方法ui-video

Animations

动画类钩子

Animation hooks usually interpolate numeric values over time.
TopicDescriptionReference
useRafRe-renders component on each requestAnimationFrameanimations-raf
useIntervalRe-renders component on a set intervalanimations-interval
useHarmonicIntervalFnHarmonic interval functionanimations-harmonic-interval
useSpringInterpolates number over time according to spring dynamicsanimations-spring
useTimeoutRe-renders component after a timeoutanimations-timeout
useTimeoutFnCalls given function after a timeoutanimations-timeout-fn
useTweenRe-renders component while tweening a number from 0 to 1animations-tween
useUpdateReturns a callback which re-renders component when calledanimations-update
动画类钩子通常会随时间插值计算数值。
主题描述参考链接
useRaf在每个requestAnimationFrame触发时重新渲染组件animations-raf
useInterval按设定的时间间隔重新渲染组件animations-interval
useHarmonicIntervalFn调和间隔函数animations-harmonic-interval
useSpring根据弹簧动力学随时间插值计算数值animations-spring
useTimeout超时后重新渲染组件animations-timeout
useTimeoutFn超时后调用指定函数animations-timeout-fn
useTween在数值从0到1的补间动画过程中重新渲染组件animations-tween
useUpdate返回一个回调函数,调用时会重新渲染组件animations-update

Side-effects

副作用类钩子

Side-effect hooks allow your app to trigger various side-effects using browser's API.
TopicDescriptionReference
useAsyncResolves an async functionside-effects-async
useAsyncFnAsync function with manual executionside-effects-async-fn
useAsyncRetryAsync function with retry capabilityside-effects-async-retry
useBeforeUnloadShows browser alert when user tries to reload or close the pageside-effects-before-unload
useCookieProvides way to read, update and delete a cookieside-effects-cookie
useCopyToClipboardCopies text to clipboardside-effects-copy-to-clipboard
useDebounceDebounces a functionside-effects-debounce
useErrorError dispatcherside-effects-error
useFaviconSets favicon of the pageside-effects-favicon
useLocalStorageManages a value in localStorageside-effects-local-storage
useSessionStorageManages a value in sessionStorageside-effects-session-storage
useLockBodyScrollLocks scrolling of the body elementside-effects-lock-body-scroll
useRafLoopCalls given function inside the RAF loopside-effects-raf-loop
useThrottleThrottles a functionside-effects-throttle
useThrottleFnThrottle function variantside-effects-throttle-fn
useTitleSets title of the pageside-effects-title
usePermissionQuery permission status for browser APIsside-effects-permission
副作用类钩子允许你的应用通过浏览器API触发各类副作用操作。
主题描述参考链接
useAsync解析异步函数side-effects-async
useAsyncFn支持手动执行的异步函数side-effects-async-fn
useAsyncRetry支持重试功能的异步函数side-effects-async-retry
useBeforeUnload当用户尝试刷新或关闭页面时显示浏览器提示side-effects-before-unload
useCookie提供读取、更新和删除Cookie的方法side-effects-cookie
useCopyToClipboard将文本复制到剪贴板side-effects-copy-to-clipboard
useDebounce为函数添加防抖功能side-effects-debounce
useError错误分发器side-effects-error
useFavicon设置页面的图标side-effects-favicon
useLocalStorage管理localStorage中的值side-effects-local-storage
useSessionStorage管理sessionStorage中的值side-effects-session-storage
useLockBodyScroll锁定body元素的滚动side-effects-lock-body-scroll
useRafLoop在RAF循环中调用指定函数side-effects-raf-loop
useThrottle为函数添加节流功能side-effects-throttle
useThrottleFn节流函数的变体side-effects-throttle-fn
useTitle设置页面标题side-effects-title
usePermission查询浏览器API的权限状态side-effects-permission

Lifecycles

生命周期类钩子

Lifecycle hooks modify and extend built-in React hooks or imitate React Class component lifecycle patterns.
TopicDescriptionReference
useEffectOnceModified useEffect that only runs oncelifecycles-effect-once
useEventSubscribe to eventslifecycles-event
useLifecyclesCalls mount and unmount callbackslifecycles-lifecycles
useMountedStateTracks if component is mountedlifecycles-mounted-state
useUnmountPromiseTrack if component is mounted with promise supportlifecycles-unmount-promise
usePromiseResolves promise only while component is mountedlifecycles-promise
useLoggerLogs in console as component goes through life-cycleslifecycles-logger
useMountCalls mount callbackslifecycles-mount
useUnmountCalls unmount callbackslifecycles-unmount
useUpdateEffectRun an effect only on updateslifecycles-update-effect
useIsomorphicLayoutEffectuseLayoutEffect that works on serverlifecycles-isomorphic-layout-effect
useDeepCompareEffectuseEffect with deep comparisonlifecycles-deep-compare-effect
useShallowCompareEffectuseEffect with shallow comparisonlifecycles-shallow-compare-effect
useCustomCompareEffectuseEffect with custom comparison functionlifecycles-custom-compare-effect
生命周期类钩子修改并扩展内置React钩子,或模拟React类组件的生命周期模式。
主题描述参考链接
useEffectOnce仅运行一次的修改版useEffectlifecycles-effect-once
useEvent订阅事件lifecycles-event
useLifecycles调用挂载和卸载回调函数lifecycles-lifecycles
useMountedState跟踪组件是否已挂载lifecycles-mounted-state
useUnmountPromise结合Promise支持跟踪组件是否已挂载lifecycles-unmount-promise
usePromise仅在组件已挂载时解析Promiselifecycles-promise
useLogger在组件生命周期各阶段输出控制台日志lifecycles-logger
useMount调用挂载回调函数lifecycles-mount
useUnmount调用卸载回调函数lifecycles-unmount
useUpdateEffect仅在组件更新时执行副作用lifecycles-update-effect
useIsomorphicLayoutEffect可在服务端运行的useLayoutEffectlifecycles-isomorphic-layout-effect
useDeepCompareEffect支持深度比较的useEffectlifecycles-deep-compare-effect
useShallowCompareEffect支持浅比较的useEffectlifecycles-shallow-compare-effect
useCustomCompareEffect支持自定义比较函数的useEffectlifecycles-custom-compare-effect

State

状态管理类钩子

State hooks allow you to easily manage state of booleans, arrays, and maps.
TopicDescriptionReference
createMemoFactory of memoized hooksstate-create-memo
createReducerFactory of reducer hooks with custom middlewarestate-create-reducer
createReducerContextFactory of hooks for sharing state between componentsstate-create-reducer-context
createStateContextFactory of hooks for sharing state between componentsstate-create-state-context
createGlobalStateCross component shared statestate-create-global-state
useDefaultReturns the default value when state is null or undefinedstate-default
useGetSetReturns state getter get() instead of raw statestate-get-set
useGetSetStateCombination of useGetSet and useSetStatestate-get-set-state
useLatestReturns the latest state or propsstate-latest
usePreviousReturns the previous state or propsstate-previous
usePreviousDistinctLike usePrevious but with a predicatestate-previous-distinct
useObservableTracks latest value of an Observablestate-observable
useRafStateCreates setState method which only updates after requestAnimationFramestate-raf-state
useSetStateCreates setState method which works like this.setStatestate-set-state
useToggleTracks state of a booleanstate-toggle
useCounterTracks state of a numberstate-counter
useListTracks state of an arraystate-list
useMapTracks state of an objectstate-map
useSetTracks state of a Setstate-set
useQueueImplements simple queuestate-queue
useStateListCircularly iterates over an arraystate-state-list
useStateValidatorValidates state with a validator functionstate-state-validator
useStateWithHistoryStores previous state values and provides handles to travel through themstate-state-with-history
useMultiStateValidatorAlike useStateValidator but tracks multiple statesstate-multi-state-validator
useMediatedStateLike regular useState but with mediation by custom functionstate-mediated-state
useFirstMountStateCheck if current render is firststate-first-mount-state
useRendersCountCount component rendersstate-renders-count
useMethodsNeat alternative to useReducerstate-methods
状态管理类钩子允许你轻松管理布尔值、数组和映射的状态。
主题描述参考链接
createMemo记忆化钩子的工厂函数state-create-memo
createReducer带自定义中间件的reducer钩子工厂state-create-reducer
createReducerContext用于组件间共享状态的钩子工厂state-create-reducer-context
createStateContext用于组件间共享状态的钩子工厂state-create-state-context
createGlobalState跨组件共享的全局状态state-create-global-state
useDefault当状态为null或undefined时返回默认值state-default
useGetSet返回状态获取器get()而非原始状态state-get-set
useGetSetStateuseGetSet与useSetState的组合state-get-set-state
useLatest返回最新的状态或属性state-latest
usePrevious返回之前的状态或属性state-previous
usePreviousDistinct类似usePrevious但支持谓词判断state-previous-distinct
useObservable跟踪Observable的最新值state-observable
useRafState创建仅在requestAnimationFrame后更新的setState方法state-raf-state
useSetState创建类似this.setState的状态更新方法state-set-state
useToggle跟踪布尔值状态state-toggle
useCounter跟踪数值状态state-counter
useList跟踪数组状态state-list
useMap跟踪对象状态state-map
useSet跟踪Set状态state-set
useQueue实现简单的队列state-queue
useStateList循环遍历数组state-state-list
useStateValidator使用验证函数验证状态state-state-validator
useStateWithHistory存储之前的状态值并提供回溯操作state-state-with-history
useMultiStateValidator类似useStateValidator但可跟踪多个状态state-multi-state-validator
useMediatedState类似普通useState但支持自定义函数中介state-mediated-state
useFirstMountState检查当前是否为首次渲染state-first-mount-state
useRendersCount统计组件渲染次数state-renders-count
useMethodsuseReducer的简洁替代方案state-methods

Miscellaneous

其他类钩子

TopicDescriptionReference
useEnsuredForwardedRefUse a React.forwardedRef safelymisc-ensured-forwarded-ref
主题描述参考链接
useEnsuredForwardedRef安全使用React.forwardedRefmisc-ensured-forwarded-ref