Collection of essential React Hooks. Port of
libreact.
Translations: ๐จ๐ณ ๆฑ่ฏญ
npm i react-use
- Sensors
useBatteryโ tracks device battery state.useGeolocationโ tracks geo location state of user's device.useHoveranduseHoverDirtyโ tracks mouse hover state of some element.useHashโ tracks location hash value.useIdleโ tracks whether user is being inactive.useIntersectionโ tracks an HTML element's intersection.useKey,useKeyPress,useKeyboardJs, anduseKeyPressEventโ track keys.useLocationanduseSearchParamโ tracks page navigation bar location state.useLongPressโ tracks long press gesture of some element.useMediaโ tracks state of a CSS media query.useMediaDevicesโ tracks state of connected hardware devices.useMotionโ tracks state of device's motion sensor.useMouseanduseMouseHoveredโ tracks state of mouse position.useMouseWheelโ tracks deltaY of scrolled mouse wheel.useNetworkStateโ tracks the state of browser's network connection.useOrientationโ tracks state of device's screen orientation.usePageLeaveโ triggers when mouse leaves page boundaries.useScratchโ tracks mouse click-and-scrub state.useScrollโ tracks an HTML element's scroll position.useScrollingโ tracks whether HTML element is scrolling.useStartTypingโ detects when user starts typing.useWindowScrollโ tracksWindowscroll position.useWindowSizeโ tracksWindowdimensions.useMeasureanduseSizeโ tracks an HTML element's dimensions.createBreakpointโ tracksinnerWidthuseScrollbarWidthโ detects browser's native scrollbars width.usePinchZoomโ tracks pointer events to detect pinch zoom in and out status.
- UI
useAudioโ plays audio and exposes its controls.useClickAwayโ triggers callback when user clicks outside target area.useCssโ dynamically adjusts CSS.useDropanduseDropAreaโ tracks file, link and copy-paste drops.useFullscreenโ display an element or video full-screen.useSliderโ provides slide behavior over any HTML element.useSpeechโ synthesizes speech from a text string.useVibrateโ provide physical feedback using the Vibration API.useVideoโ plays video, tracks its state, and exposes playback controls.
- Animations
useRafโ re-renders component on eachrequestAnimationFrame.useIntervalanduseHarmonicIntervalFnโ re-renders component on a set interval usingsetInterval.useSpringโ interpolates number over time according to spring dynamics.useTimeoutโ re-renders component after a timeout.useTimeoutFnโ calls given function after a timeout.useTweenโ re-renders component, while tweening a number from 0 to 1.useUpdateโ returns a callback, which re-renders component when called.
- Side-effects
useAsync,useAsyncFn, anduseAsyncRetryโ resolves anasyncfunction.useBeforeUnloadโ shows browser alert when user try to reload or close the page.useCookieโ provides way to read, update and delete a cookie.useCopyToClipboardโ copies text to clipboard.useDebounceโ debounces a function.useErrorโ error dispatcher.useFaviconโ sets favicon of the page.useLocalStorageโ manages a value inlocalStorage.useLockBodyScrollโ lock scrolling of the body element.useRafLoopโ calls given function inside the RAF loop.useSessionStorageโ manages a value insessionStorage.useThrottleanduseThrottleFnโ throttles a function.useTitleโ sets title of the page.usePermissionโ query permission status for browser APIs.
- Lifecycles
useEffectOnceโ a modifieduseEffecthook that only runs once.useEventโ subscribe to events.useLifecyclesโ callsmountandunmountcallbacks.useMountedStateanduseUnmountPromiseโ track if component is mounted.usePromiseโ resolves promise only while component is mounted.useLoggerโ logs in console as component goes through life-cycles.useMountโ callsmountcallbacks.useUnmountโ callsunmountcallbacks.useUpdateEffectโ run aneffectonly on updates.useIsomorphicLayoutEffectโuseLayoutEffectthat that works on server.useDeepCompareEffect,useShallowCompareEffect, anduseCustomCompareEffect
- State
createMemoโ factory of memoized hooks.createReducerโ factory of reducer hooks with custom middleware.createReducerContextandcreateStateContextโ factory of hooks for a sharing state between components.useDefaultโ returns the default value when state isnullorundefined.useGetSetโ returns state getterget()instead of raw state.useGetSetStateโ as ifuseGetSetanduseSetStatehad a baby.useLatestโ returns the latest state or propsusePreviousโ returns the previous state or props.usePreviousDistinctโ likeusePreviousbut with a predicate to determine ifpreviousshould update.useObservableโ tracks latest value of anObservable.useRafStateโ createssetStatemethod which only updates afterrequestAnimationFrame.useSetStateโ createssetStatemethod which works likethis.setState.useStateListโ circularly iterates over an array.useToggleanduseBooleanโ tracks state of a boolean.useCounteranduseNumberโ tracks state of a number.useListandโ tracks state of an array.useUpsertuseMapโ tracks state of an object.useSetโ tracks state of a Set.useQueueโ implements simple queue.useStateValidatorโ tracks state of an object.useStateWithHistoryโ stores previous state values and provides handles to travel through them.useMultiStateValidatorโ alike theuseStateValidator, but tracks multiple states at a time.useMediatedStateโ like the regularuseStatebut with mediation by custom function.useFirstMountStateโ check if current render is first.useRendersCountโ count component renders.createGlobalStateโ cross component shared state.useMethodsโ neat alternative touseReducer.
- Miscellaneous
useEnsuredForwardedRefandensuredForwardRefโ use a React.forwardedRef safely.
Usage โ how to import.
Unlicense โ public domain.
Support โ add yourself to backer list below.