# ReactUse — Full Documentation (llms-full.txt) Website: https://reactuse.com GitHub: https://github.com/childrentime/reactuse NPM: https://www.npmjs.com/package/@reactuses/core ReactUse (@reactuses/core) is an open-source library of 110+ custom React Hooks for production applications. Hooks are TypeScript-first, tree-shakable, and SSR-compatible. Supports React 16.8 through React 19, Next.js, Remix, and other SSR frameworks. This file inlines the full Markdown for every hook documentation page. Each hook section starts with the line "URL: https://reactuse.com/{category}/{hookname}/" so passages can be cited individually. --- # State hooks (24) ## use URL: https://reactuse.com/state/use/ Category: state Description: use is a React hook that polyfills React 19's use() for v18 and below — resolve and consume promise state. For React 19 and above, use the built-in use hook. Import: `import { use } from '@reactuses/core'` # use `use` is a polyfill hook to resolve promises state for React v18 and below. Note that it only implements the ability to consume promises. For React v19 and above, you can use the built-in `use` hook: https://react.dev/reference/react/use `use` accepts a `Usable` (a promise or React context) and resolves it within a Suspense boundary. It tracks the thenable's status internally (`pending`, `fulfilled`, `rejected`) and throws the promise while pending so that a parent `` fallback is displayed. Once resolved, it returns the unwrapped value directly. This brings the React 19 `use` semantics to older React versions. ### When to Use - Loading asynchronous data inside a component tree that already uses `` boundaries - Migrating a codebase toward the React 19 `use` pattern while still supporting React 18 - Reading from a React context without the `useContext` hook for API consistency with future React versions ### Notes - **Suspense required**: The component calling `use` must be wrapped in a `` boundary; otherwise the thrown promise will be unhandled. - **Promise identity matters**: Pass a stable promise reference (e.g., created outside the render or memoized). Creating a new promise on every render will restart the loading cycle. - **Limited scope**: This polyfill only supports promises and contexts. Other usable types that React 19 may support in the future are not covered. ## Usage ```tsx live noInline const promise = new Promise((resolve) => { setTimeout(() => { resolve("resolved"); }, 5000); }); function Demo() { const data = use(promise); return

{data}

; }; render( ); ``` --- ## useBoolean URL: https://reactuse.com/state/useboolean/ Category: state Description: useBoolean is a React hook to manage a boolean state with convenient setTrue, setFalse, and toggle helpers — no inline arrow functions needed. Import: `import { useBoolean } from '@reactuses/core'` # useBoolean React state hook that manages a boolean value `useBoolean` wraps a boolean state and returns an object with the current `value` along with convenience methods: `setValue`, `setTrue`, `setFalse`, and `toggle`. This avoids the need to write inline arrow functions like `() => setState(true)` throughout your components. The hook accepts an optional initial value that defaults to `false`. ### When to Use - Controlling visibility of modals, drawers, tooltips, or other disclosure UI with explicit `setTrue`/`setFalse` semantics - Managing feature flags or on/off states where named helpers improve readability over raw `useState` - Any scenario where you want a richer API than a plain `[boolean, setter]` tuple ### Notes - **SSR-safe**: Uses only React state internally, so it works identically on server and client. - **Object return**: Unlike `useToggle` which returns a tuple, `useBoolean` returns a named object, making it easier to destructure only the methods you need. - See also `useToggle` for a minimal tuple-based boolean hook and `useDisclosure` for modal-oriented open/close patterns with callback support. ## Usage ```tsx live function Demo() { const { value, setValue, setTrue, setFalse, toggle } = useBoolean(false); return (

Current value: {value ? 'True' : 'False'}

Status: {value ? '✅ Enabled' : '❌ Disabled'}

); }; ``` --- ## useControlled URL: https://reactuse.com/state/usecontrolled/ Category: state Description: useControlled is a React hook for components that work as both controlled and uncontrolled — returns a useState-like tuple that mirrors props or internal state. Import: `import { useControlled } from '@reactuses/core'` # useControlled `useControlled` is a custom hook that helps you manage controlled components. It is a wrapper around `useState` that allows you to control the value of a component from the outside. `useControlled` returns a `[value, setValue]` tuple that behaves like `useState` when the first argument is `undefined` (uncontrolled mode), or mirrors the provided value when it is defined (controlled mode). An optional `onChange` callback is invoked whenever the value changes. This pattern is essential for building components that need to work both as controlled and uncontrolled inputs. ### When to Use - Building reusable form components (inputs, selects, sliders) that must support both controlled and uncontrolled usage - Wrapping third-party components that require a controlled interface while still providing a sensible uncontrolled default - Implementing component libraries where consumers decide whether to own the state or let the component manage it ### Notes - **No mode switching**: The hook does not support switching between controlled and uncontrolled modes after initial mount. Choose one mode at creation time. - **No function updater**: Unlike `useState`, the setter does not accept a `(prev) => next` function form. Pass values directly. - See also `useSetState` for a class-component-style partial state updater. :::note The `useControlled` component does not support switching between controlled and uncontrolled modes, nor does it support passing a function for state updates. You can refer to this discussion for more information: https://github.com/adobe/react-spectrum/issues/2320. ::: ## Usage ```tsx live function Demo() { const [state, setState] = useState(""); const [value, setValue] = useControlled(state, ""); const [value1, setValue1] = useControlled(undefined, "unControlled value"); const handleChange = (event) => { setState(event.target.value); }; const handleChange1 = (event) => { setValue1(event.target.value); }; return ( <>

Controlled Value: {value}

); }; ``` --- ## useCookie URL: https://reactuse.com/state/usecookie/ Category: state Description: useCookie is a React hook to store, update, and delete a browser cookie by key — returns the value plus update and refresh functions, with js-cookie options. Import: `import { useCookie } from '@reactuses/core'` # useCookie React hook that facilitates the storage, updating and deletion of values within the CookieStore `useCookie` manages a single browser cookie by key. It returns a tuple of `[cookieValue, updateCookie, refreshCookie]`. Call `updateCookie` with a string to set the cookie or with `undefined` to delete it. The `refreshCookie` function re-reads the cookie from the store, which is useful when the cookie may have been modified externally. Options are passed through to `js-cookie` for controlling path, domain, expiration, and other cookie attributes. ### When to Use - Persisting user preferences (locale, theme, consent flags) in cookies for server-side access - Reading and writing authentication or session tokens stored in cookies - Synchronizing cookie state in a component when external code (analytics, third-party scripts) may also modify the cookie ### Notes - **SSR considerations**: Pass a `defaultValue` when using SSR so the hook has a value before `document.cookie` is available on the client. - **Same-tab sync**: Updating a cookie in one component automatically re-renders sibling `useCookie` instances using the same key in the same tab. Cookies fire no native cross-tab event, so this does **not** propagate across tabs (unlike `useLocalStorage`/`useSessionStorage`). - **`refreshCookie`**: Only needed to pick up changes made *outside* the hook — a server `Set-Cookie`, a direct `document.cookie` write, or the CookieStore API. Sibling hook instances no longer need it. :::note `useCookie` instances that share the same key stay in sync within the same tab: calling `updateCookie` in one component re-renders the others automatically. (Earlier versions did not — a manual broadcast was required; that is no longer necessary.) ::: ## Usage ```tsx live function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value" ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore as any; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return (

Click on the button to update or clear the cookie

cookie: {cookieValue || "no value"}

); }; ``` ## Same-tab sync Two components using the same cookie key stay in sync within the tab — click a button in either panel and the other updates immediately, no manual broadcast and no reload: ```tsx live noInline function CookiePanel({ label }) { const [value, updateCookie] = useCookie("shared-demo-cookie", { path: "/" }, "A"); return (
{label} reads: {value ?? "(empty)"}
); } function Demo() { return (

Click a button in either panel — the other updates in the same tab:

); } render(); ``` --- ## useCountDown URL: https://reactuse.com/state/usecountdown/ Category: state Description: useCountDown is a React hook that counts down from a duration in seconds — returns formatted hour, minute, and second strings and fires a callback at zero. Import: `import { useCountDown } from '@reactuses/core'` # useCountDown React State Hooks that return the minutes gracefull `useCountDown` accepts a duration in seconds and returns a `[hour, minute, second]` tuple of formatted strings that update every second. An optional `format` function lets you customize the string formatting, and an optional `callback` is invoked when the countdown reaches zero. The hook handles the interval lifecycle automatically, cleaning up on unmount. ### When to Use - Displaying countdown timers for sales, events, or limited-time offers - Building exam or quiz timers that trigger an action when time expires - Showing time remaining until a scheduled event (e.g., midnight, a launch date) ### Notes - **SSR compatibility**: When rendering on the server, ensure the initial `time` value is computed identically on both server and client to avoid hydration mismatches. The demo uses `suppressHydrationWarning` for this reason. - **Custom formatting**: The default format produces `HH:MM:SS` strings. Pass a custom `format` function to change the output (e.g., zero-padding, localized labels). - **Completion callback**: The optional third argument fires once when the countdown reaches zero, useful for redirects, alerts, or state transitions. ## Usage ```tsx live function Demo() { const now = new Date(); const tomorrow = new Date(); tomorrow.setDate(now.getDate() + 1); tomorrow.setHours(0, 0, 0, 0); const diffInSec = Math.floor((tomorrow.getTime() - now.getTime()) / 1000); // note: If your app is running in server side, must pass the same time as the client // this demo is not running in server side const [hour, minute, second] = useCountDown(diffInSec); return (
{`${hour}:${minute}:${second}`}
); }; ``` --- ## useCounter URL: https://reactuse.com/state/usecounter/ Category: state Description: useCounter is a React hook to manage a numeric counter with inc, dec, set, and reset helpers and optional min and max clamping. Import: `import { useCounter } from '@reactuses/core'` # useCounter React state hook that tracks a numeric value `useCounter` manages an integer counter with built-in `inc`, `dec`, `set`, and `reset` functions. It returns a tuple of `[current, set, inc, dec, reset]`. You can optionally specify `max` and `min` bounds; the counter will be clamped to stay within those limits. The initial value defaults to `0` and can be a number or a function returning a number. ### When to Use - Implementing quantity selectors, pagination controls, or stepper inputs - Tracking scores, votes, or item counts with enforced minimum/maximum boundaries - Any numeric state that benefits from dedicated increment, decrement, and reset actions ### Notes - **Bounded values**: When `max` or `min` is provided, the counter is clamped after every operation. Setting a value outside the bounds will be silently adjusted. - **SSR-safe**: Uses only React state internally with no browser API dependencies. - See also `useCycleList` for cycling through a fixed list of items rather than an open numeric range. ## Usage ```tsx live function Demo() { const [current, set, inc, dec, reset] = useCounter(10, 100, 1); return (

{current} max: 100; min: 1;

); }; ``` --- ## useCycleList URL: https://reactuse.com/state/usecyclelist/ Category: state Description: useCycleList is a React hook to cycle through a list of items — returns the current item plus next and prev functions with wraparound behavior. Import: `import { useCycleList } from '@reactuses/core'` # useCycleList Cycle through a list of items `useCycleList` takes an array of items and returns a tuple of `[currentItem, next, prev]`. Calling `next()` advances to the next item in the list, wrapping around to the beginning when the end is reached. Calling `prev()` moves backward with the same wraparound behavior. You can optionally pass a starting index and also jump by more than one step by passing an offset to `next` or `prev`. ### When to Use - Cycling through theme options, color schemes, or display modes - Building carousels or slideshows that loop through a set of items - Rotating through a list of predefined values (e.g., font sizes, sort orders) ### Notes - **Generic type**: The hook is fully generic; the list can contain any type (strings, numbers, objects, etc.). - **SSR-safe**: Uses only React state with no browser API dependencies. - See also `useCounter` for cycling through a numeric range with min/max bounds. ## Usage ```tsx live function Demo() { const [state, next, prev] = useCycleList([ "Dog", "Cat", "Lizard", "Shark", "Whale", "Dolphin", "Octopus", "Seal", ]); return (
{state}
); }; ``` --- ## useDebounce URL: https://reactuse.com/state/usedebounce/ Category: state Description: useDebounce is a React hook that returns a debounced copy of a value — updates only after the input stops changing for the given delay. Import: `import { useDebounce } from '@reactuses/core'` # useDebounce React hooks that [debounce](https://lodash.com/docs/4.17.15#debounce) value `useDebounce` accepts a value and a wait time in milliseconds, and returns a debounced version of that value. The returned value only updates after the specified delay has elapsed since the last change to the input value. Under the hood it uses `lodash.debounce`, so you can pass the same options (`leading`, `trailing`, `maxWait`) for fine-grained control. ### When to Use - Delaying search input to avoid firing API requests on every keystroke - Throttling expensive re-renders triggered by rapidly changing values (e.g., window resize dimensions) - Smoothing out form validation so error messages do not flicker while the user is still typing ### Notes - **Value-level debounce**: This hook debounces the *value* itself, not a callback. If you need to debounce a function, use `useDebounceFn` instead. - **Options passthrough**: The third argument is forwarded directly to `lodash.debounce`, supporting `leading`, `trailing`, and `maxWait`. - See also `useThrottle` for rate-limiting value updates at a fixed interval rather than delaying until idle. ## Usage ```tsx live function Demo() { const [value, setValue] = useState(""); const debouncedValue = useDebounce(value, 500); return (
setValue(e.target.value)} placeholder="Typed value" style={{ width: 280 }} />

DebouncedValue: {debouncedValue}

); }; ``` --- ## useDisclosure URL: https://reactuse.com/state/usedisclosure/ Category: state Description: useDisclosure is a React hook for disclosure widgets like modals and dropdowns — manages open and close state with controlled and uncontrolled modes. Import: `import { useDisclosure } from '@reactuses/core'` # useDisclosure `useDisclosure` is a hook that provides all the tools you need to create a disclosure widget. Disclosure widgets are used to show or hide content. This hook provides the state and functions to control the visibility of the content. `useDisclosure` returns an object with `isOpen`, `onOpen`, `onClose`, and `onOpenChange` along with an `isControlled` flag. It supports both controlled mode (pass `isOpen` via props) and uncontrolled mode (uses internal state with an optional `defaultOpen`). Callbacks for `onOpen`, `onClose`, and `onChange` can be provided in the props to run side effects when the state transitions. ### When to Use - Managing modal, dialog, or drawer open/close state with lifecycle callbacks - Building collapsible panels, accordions, or expandable sections - Any disclosure pattern where you need both controlled and uncontrolled support with open/close event hooks ### Notes - **Controlled and uncontrolled**: Pass `isOpen` in props for controlled mode. Omit it (or leave it `undefined`) for uncontrolled mode with optional `defaultOpen`. - **Callback support**: Unlike simpler boolean hooks, `useDisclosure` accepts `onOpen`, `onClose`, and `onChange` callbacks, making it well-suited for side effects like analytics or focus management. - See also `useBoolean` for a simpler boolean state hook without callbacks, and `useToggle` for a minimal tuple-based toggle. ## Usage ```tsx live function Demo() { const { isOpen, onOpen, onClose } = useDisclosure(); return ( <>

{isOpen ? "Open" : "Close"}

); }; ``` --- ## useFirstMountState URL: https://reactuse.com/state/usefirstmountstate/ Category: state Description: useFirstMountState is a React hook that returns true on the initial render and false on every render after — synchronous, with no extra re-render. Import: `import { useFirstMountState } from '@reactuses/core'` # useFirstMountState React state hook that returns true if component is just mounted `useFirstMountState` returns `true` during the component's initial render and `false` on all subsequent renders. It uses a ref internally so the check is synchronous and does not trigger additional re-renders. This is useful for skipping logic that should only run after the first paint or for distinguishing the initial mount from updates. ### When to Use - Skipping animations or transitions on the very first render so the component appears instantly - Conditionally running effect logic only on updates (not on mount) by combining with `useEffect` - Displaying "new" or "just loaded" indicators that disappear after the first re-render ### Notes - **Synchronous check**: The returned value is available immediately during render, not deferred to an effect. - **SSR-safe**: Works identically on server and client since it only uses a React ref internally. - See also `useMountedState` for a function-based approach that checks whether the component is currently mounted (as opposed to whether it is on its *first* render). ## Usage ```tsx live function Demo() { const isFirstMount = useFirstMountState(); const [render, reRender] = useState(0); return (
This component is just mounted: {isFirstMount ? "YES" : "NO"}
); }; ``` --- ## useHover URL: https://reactuse.com/state/usehover/ Category: state Description: useHover is a React hook that returns whether the mouse is hovering over a referenced element, via mouseenter and mouseleave listeners. Import: `import { useHover } from '@reactuses/core'` # useHover Detect if mouse is over given element. `useHover` accepts a ref to a DOM element and returns a boolean indicating whether the mouse is currently hovering over that element. It attaches `mouseenter` and `mouseleave` event listeners internally and cleans them up on unmount. The returned value updates reactively, triggering a re-render whenever the hover state changes. ### When to Use - Showing tooltips, popovers, or contextual information when the user hovers over an element - Highlighting or enlarging UI elements on hover without CSS-only solutions (e.g., when you need to trigger side effects) - Conditionally rendering content or fetching data based on hover intent ### Notes - **Ref-based target**: Pass a React ref object. The hook handles attaching and detaching event listeners automatically. - **Mouse only**: This hook tracks mouse events (`mouseenter`/`mouseleave`). It does not detect touch-based hover on mobile devices. - See also `useTextSelection` for tracking what the user has selected, or the browser-category hooks for other pointer-related utilities. ## Usage ```tsx live function Demo() { const ref = useRef(null); const hovered = useHover(ref); return
{hovered ? "true" : "false"}
; }; ``` --- ## useLatest URL: https://reactuse.com/state/uselatest/ Category: state Description: useLatest is a React hook that returns a ref to the latest value — access current props or state inside async callbacks without stale closures. Import: `import { useLatest } from '@reactuses/core'` # useLatest React state hook that returns the latest state as described in the [React hooks FAQ](https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function). This is mostly useful to get access to the latest value of some props or state inside an asynchronous callback, instead of that value at the time the callback was created from. `useLatest` accepts any value and returns a `MutableRefObject` whose `.current` property always holds the most recent value. The ref is updated synchronously on every render, so reading `ref.current` inside timeouts, intervals, or event handlers always gives you the up-to-date value rather than a stale closure capture. ### When to Use - Accessing the latest state or props inside `setTimeout`, `setInterval`, or other asynchronous callbacks - Avoiding stale closures in event handlers that are registered once but need to reference changing values - Passing the latest value into imperative code (e.g., third-party library callbacks) without re-registering listeners ### Notes - **Not a state hook**: The returned ref does not trigger re-renders when updated. It is meant to be read inside callbacks, not used as a render dependency. - **SSR-safe**: Uses only a React ref internally with no browser dependencies. - See also `usePrevious` for tracking the value from the prior render rather than the current one. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const latestCount = useLatest(count); const handleAlertClick = () => { setTimeout(() => { alert(`Latest count value: ${latestCount.current}`); }, 3000); }; return (

You clicked {count} times

); }; ``` --- ## useLocalStorage URL: https://reactuse.com/state/uselocalstorage/ Category: state Description: useLocalStorage is a React hook that binds state to a localStorage key — a useState-like tuple with SSR safety, custom serializers, and cross-tab sync. Import: `import { useLocalStorage } from '@reactuses/core'` # useLocalStorage React side-effect hook that manages a single `localStorage` key `useLocalStorage` binds a React state to a `localStorage` key. It returns a `[value, setValue]` tuple similar to `useState`. The value is read from storage on mount and written back whenever you call `setValue`. Setting the value to `null` removes the key. Custom serializers can be provided for non-string data types, and the hook listens for cross-tab `storage` events by default so that changes in one tab are reflected in others. ### When to Use - Persisting user preferences (theme, language, layout) across page reloads - Caching form drafts or application state so users can resume where they left off - Sharing simple state between browser tabs via the `storage` event ### Notes - **Persistence**: Data survives page reloads and browser restarts. Use `useSessionStorage` if you only need data for the current session. - **Cross-tab & same-tab sync**: Every component bound to the same key stays in sync — within the current tab (always on, no reload) and across other tabs (via the `storage` event). `listenToStorageChanges: false` disables only the cross-tab listener; same-tab sync stays active. - **Custom serialization**: For objects or non-string values, provide `serializer.read` and `serializer.write` functions in the options. The default behavior uses JSON serialization for objects and raw strings for string values. - See also `useSessionStorage` for session-scoped storage and `useCookie` for cookie-based persistence. ## Usage ```tsx live function Demo() { // bind string const [value, setValue] = useLocalStorage("my-key", "key"); // bind object with custom serializer const [myObj, setMyObj] = useLocalStorage( "myObj", { name: "test", }, { serializer: { read: (val) => { console.log("read", val); return JSON.parse(val); }, write: (val) => { console.log("write", val); return JSON.stringify(val); }, }, } ); return (

String Value

Value: {value}

Object Value

Object: {JSON.stringify(myObj)}
); }; ``` ## Same-tab sync Two components bound to the same key stay in sync within the tab — not just across tabs. Click a button in one panel and the other updates immediately, no reload: ```tsx live noInline function StoragePanel({ label }) { const [value, setValue] = useLocalStorage("shared-demo-key", "A"); return (
{label} reads: {String(value ?? "(empty)")}
); } function Demo() { return (

Click a button in one panel — the other updates in the same tab:

); } render(); ``` --- ## useMap URL: https://reactuse.com/state/usemap/ Category: state Description: useMap is a React hook to manage a JavaScript Map in state — exposes set, get, remove, has, clear, and reset methods that trigger re-renders automatically. Import: `import { useMap } from '@reactuses/core'` # useMap React state hook that manages a Map `useMap` wraps a JavaScript `Map` in React state and exposes a rich set of methods: `set`, `get`, `remove`, `has`, `clear`, and `reset`, along with the current `map` instance and its `size`. Mutations through these methods trigger re-renders automatically. The initial value can be a `Map` instance, an array of key-value pairs, or a factory function. ### When to Use - Managing key-value collections (e.g., selected items, tag mappings, lookup tables) that change frequently - Building dynamic forms or configuration editors where entries are added and removed at runtime - Any scenario where you need `Map` semantics (ordered keys, non-string keys) with reactive state updates ### Notes - **Immutable updates**: Each mutation creates a new `Map` instance internally so React detects the state change and re-renders. - **Reset support**: The `reset` function restores the map to its initial value, which is useful for "undo" or "clear filters" actions. - **SSR-safe**: Uses only React state internally with no browser API dependencies. ## Usage ```tsx live function Demo() { const { map, set, get, remove, has, clear, reset, size } = useMap([ ['react', '18.0.0'], ['vue', '3.0.0'], ]); return (

Map size: {size}

Current entries:

    {Array.from(map.entries()).map(([key, value]) => (
  • {key}: {value} {has(key) && ' ✓'}
  • ))}

Get React version: {get('react') || 'Not found'}

); }; ``` --- ## useMergedRefs URL: https://reactuse.com/state/usemergedrefs/ Category: state Description: useMergedRefs is a React hook that merges multiple refs into a single callback ref — attach more than one ref to the same DOM node with a stable ref. Import: `import { useMergedRefs } from '@reactuses/core'` # useMergedRefs `useMergedRefs` is a hook that merges multiple refs into a single ref. Use this hook when you need to use more than one ref on a single dom node. `useMergedRefs` accepts any number of refs (callback refs, `RefObject`s, or `undefined`) and returns a single callback ref that forwards the DOM node to all of them. This eliminates the need to manually synchronize multiple refs on the same element. The returned ref is stable and handles both ref objects and callback refs uniformly. ### When to Use - Combining a forwarded ref from `React.forwardRef` with an internal ref used by another hook (e.g., `useHover`, `useFocus`) - Attaching multiple independent behaviors (measurement, intersection observation, drag handling) to the same DOM element - Building compound components or component libraries where both the library and the consumer need ref access ### Notes - **Handles all ref types**: Works with `RefObject`, callback refs, and `undefined` values seamlessly. - **SSR-safe**: The returned callback ref does not access any browser APIs on its own. - See also `useHover` and other element hooks that accept refs, which can be combined via `useMergedRefs`. ## Usage ```tsx live noInline function Demo() { const hoverRef = useRef(null); const buttonRef = useRef(null); const isHovered = useHover(hoverRef); const [isFocused, toggleFocus] = useToggle(false); const mergedRef = useMergedRefs(hoverRef, buttonRef); useEffect(() => { const handleKeyPress = (event) => { if (event.key === 'f' || event.key === 'F') { buttonRef.current?.focus(); } }; window.addEventListener('keypress', handleKeyPress); return () => { window.removeEventListener('keypress', handleKeyPress); }; }, []); const handleFocus = () => toggleFocus(true); const handleBlur = () => toggleFocus(false); return (

Press 'F' key to focus the button

); }; render(); ``` --- ## useMountedState URL: https://reactuse.com/state/usemountedstate/ Category: state Description: useMountedState is a React hook that returns a function to check whether the component is still mounted — guard against state updates after unmount. Import: `import { useMountedState } from '@reactuses/core'` # useMountedState Lifecycle hook providing ability to check component's mount state. Returns a function that will return `true` if component mounted and `false` otherwise `useMountedState` returns a function (not a value) that you can call at any time to check whether the component is still mounted. This is particularly useful inside asynchronous operations where you need to guard against setting state on an unmounted component. The function is stable across re-renders and always reflects the current mount status. ### When to Use - Guarding `setState` calls inside async operations (`fetch`, `setTimeout`) to prevent "state update on unmounted component" warnings - Conditionally executing cleanup or follow-up logic only if the component is still in the DOM - Implementing safe polling or subscription patterns that should stop when the component unmounts ### Notes - **Function return**: Unlike `useFirstMountState` which returns a boolean, this hook returns a *function* that returns a boolean. Call it (`isMounted()`) to get the current status. - **SSR-safe**: The function returns `false` during server-side rendering and becomes `true` after the component mounts on the client. - See also `useFirstMountState` for detecting only the initial mount rather than ongoing mount status. ## Usage ```tsx live function Demo() { const isMounted = useMountedState(); const [, update] = useState(0); useEffect(() => { update(1); }, []); return
This component is {isMounted() ? "MOUNTED" : "NOT MOUNTED"}
; }; ``` --- ## usePrevious URL: https://reactuse.com/state/useprevious/ Category: state Description: usePrevious is a React hook that returns a value from the previous render — useful for comparing the current and prior state or props. Import: `import { usePrevious } from '@reactuses/core'` # usePrevious React state hook that returns the previous state as described in the [React Docs](https://react.dev/reference/react/useState#storing-information-from-previous-renders) `usePrevious` accepts a value and returns the value from the previous render. On the initial render it returns `undefined` since there is no prior value. The hook stores the previous value in a ref and updates it after each render, giving you a snapshot of what the value was before the most recent change. ### When to Use - Comparing current and previous values to trigger animations, transitions, or conditional logic - Detecting direction of change (e.g., whether a counter increased or decreased) - Implementing undo functionality or displaying "changed from X to Y" indicators ### Notes - **Initial value**: Returns `undefined` on the first render. Type the result as `T | undefined` accordingly. - **SSR-safe**: Uses only a React ref internally with no browser dependencies. - See also `useLatest` for accessing the *current* (most recent) value inside callbacks without stale closures. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return (

Now: {count}, before: {prevCount}

); }; ``` --- ## useRafState URL: https://reactuse.com/state/userafstate/ Category: state Description: useRafState is a React hook with the same API as useState that defers updates to the next animation frame — batches high-frequency changes. Import: `import { useRafState } from '@reactuses/core'` # useRafState React state hook that only updates state in the callback of [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) `useRafState` has the same API as `useState` but defers state updates to the next animation frame via `requestAnimationFrame`. This batches rapid state changes (such as those from mouse or scroll events) into a single update per frame, reducing unnecessary re-renders and improving performance for high-frequency updates. ### When to Use - Tracking mouse position, scroll offset, or window dimensions where events fire far more often than the screen refreshes - Smoothing out state updates from sensors or streams that produce data faster than 60fps - Reducing render overhead for any state that changes very rapidly and is used primarily for visual output ### Notes - **Browser-only**: `requestAnimationFrame` is not available during SSR. The hook still works, but updates will not be batched on the server. - **Same API as useState**: The returned tuple is `[state, setState]` with the same `SetStateAction` signature, so it is a drop-in replacement. - **Automatic cleanup**: Pending animation frame requests are cancelled on unmount to prevent memory leaks. ## Usage ```tsx live function Demo() { const [state, setState] = useRafState({ x: 0, y: 0 }); useMount(() => { const onMouseMove = (event: MouseEvent) => { setState({ x: event.clientX, y: event.clientY }); }; const onTouchMove = (event: TouchEvent) => { setState({ x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY, }); }; document.addEventListener("mousemove", onMouseMove); document.addEventListener("touchmove", onTouchMove); return () => { document.removeEventListener("mousemove", onMouseMove); document.removeEventListener("touchmove", onTouchMove); }; }); return
{JSON.stringify(state, null, 2)}
; }; ``` --- ## useSessionStorage URL: https://reactuse.com/state/usesessionstorage/ Category: state Description: useSessionStorage is a React hook that binds state to a sessionStorage key — a useState-like tuple with SSR safety, custom serializers, and cross-tab sync. Import: `import { useSessionStorage } from '@reactuses/core'` # useSessionStorage React side-effect hook that manages a single `sessionStorage` key `useSessionStorage` binds a React state to a `sessionStorage` key. It returns a `[value, setValue]` tuple that behaves like `useState`. The value is read from session storage on mount and written back on updates. Setting the value to `null` removes the key. Like `useLocalStorage`, it supports custom serializers and listens for cross-tab `storage` events by default. ### When to Use - Storing temporary state that should persist across page navigations within the same tab but not across browser restarts - Keeping wizard or multi-step form progress that resets when the user closes the tab - Caching data that is sensitive or session-specific (e.g., one-time tokens, temporary filters) ### Notes - **Session-scoped**: Unlike `localStorage`, data in `sessionStorage` is cleared when the tab or browser is closed. Use `useLocalStorage` for long-lived persistence. - **Same-tab sync**: Components bound to the same key in one tab stay in sync — updating one re-renders the others without a reload. (`sessionStorage` is per-tab, so this does not cross tabs.) The cross-tab `storage` listener is on by default; disable it with `listenToStorageChanges: false`. - **Custom serialization**: Provide `serializer.read` and `serializer.write` in the options for non-string data types. - See also `useLocalStorage` for persistent storage and `useCookie` for cookie-based persistence. ## Usage ```tsx live function Demo() { // bind string const [value, setValue] = useSessionStorage("my-key", "key"); return (
Value: {value}
{/* delete data from storage */}
); }; ``` --- ## useSetState URL: https://reactuse.com/state/usesetstate/ Category: state Description: useSetState is a React hook that returns a useState tuple where the setter merges a partial object into state — like this.setState in class components. Import: `import { useSetState } from '@reactuses/core'` # useSetState useState wrapper to work with state like in class component `useSetState` returns a `[state, setState]` tuple where `setState` accepts a *partial* object (or a function returning a partial object) and merges it into the current state, just like `this.setState` in React class components. This avoids the need to spread the previous state manually when updating a single field in an object. ### When to Use - Managing complex form state with many fields where you want to update one field at a time without spreading the rest - Migrating class components to hooks while preserving the familiar `this.setState({ key: value })` pattern - Any scenario involving an object state where partial updates are more ergonomic than full replacements ### Notes - **Shallow merge**: The partial object is merged one level deep via object spread. Nested objects are replaced, not deeply merged. - **Function updater**: You can pass a function `(currentState) => Partial` for updates that depend on the current state. - **SSR-safe**: Uses only React state internally with no browser dependencies. ## Usage ```tsx live function Demo() { const [state, setState] = useSetState({ value1: "value1", value2: "value2" }); const { value1, value2 } = state; return (

value1: {value1}

value2: {value2}

); }; ``` --- ## useSupported URL: https://reactuse.com/state/usesupported/ Category: state Description: useSupported is a React hook for browser feature detection — runs a check after mount and returns a boolean, safely returning false during SSR. Import: `import { useSupported } from '@reactuses/core'` # useSupported Check to see if your browser supports some feature `useSupported` accepts a callback that performs a feature-detection check (e.g., `() => 'IntersectionObserver' in window`) and returns a boolean indicating whether the feature is available. The check runs after mount in a `useEffect` (or `useLayoutEffect` if the `sync` option is `true`), so it safely returns `false` during SSR and on the initial server render. ### When to Use - Conditionally enabling browser features (e.g., EyeDropper API, Clipboard API, Web Bluetooth) based on runtime availability - Showing fallback UI or informational messages when a required API is not supported - Gating hook logic that depends on a specific browser capability to avoid runtime errors ### Notes - **SSR-safe**: Always returns `false` on the server and during the initial render, then updates to the true value after mount. - **Sync mode**: Pass `sync: true` to run the check in `useLayoutEffect` instead of `useEffect`, which can prevent a flash of incorrect UI. - This hook is used internally by many other hooks in this library (e.g., `useEyeDropper`, `useClipboard`) to gate browser API access. ## Usage ```tsx live function Demo() { const isSupported = useSupported(() => "EyeDropper" in window); return (

window.EyeDropper is {isSupported ? "supported" : "unsupported"} in your browser

); }; ``` --- ## useTextSelection URL: https://reactuse.com/state/usetextselection/ Category: state Description: useTextSelection is a React hook that reactively tracks the user's text selection via the selectionchange event — returns the current Selection object, or null. Import: `import { useTextSelection } from '@reactuses/core'` # useTextSelection Track user text selection based on [document.getSelection](https://developer.mozilla.org/en-US/docs/Web/API/Document/getSelection) `useTextSelection` listens for `selectionchange` events on the document and returns the current `Selection` object (or `null` if nothing is selected). The returned object updates reactively whenever the user selects, modifies, or clears a text selection anywhere on the page. You can call `.toString()` on the result to get the selected text as a string. ### When to Use - Building annotation or highlighting tools that respond to user text selections - Displaying floating toolbars (bold, italic, link) when the user selects text in an editor - Tracking selected text for search, copy, or share-to-social features ### Notes - **Document-wide**: The hook tracks selections across the entire document, not a specific element. Filter by checking the selection's anchor or focus node if you need element-scoped behavior. - **Browser-only**: `document.getSelection` is not available during SSR. The hook returns `null` on the server. - The returned `Selection` object is a live reference from the browser; its properties update in place between re-renders. ## Usage ```tsx live function Demo() { const selection = useTextSelection(); return (

Select some text here or anywhere on the page and it will be displayed below

Selected text: {selection?.toString()}
); }; ``` --- ## useThrottle URL: https://reactuse.com/state/usethrottle/ Category: state Description: useThrottle is a React hook that returns a throttled copy of a value — updates at most once per interval for a steady stream of changes. Import: `import { useThrottle } from '@reactuses/core'` # useThrottle React hooks that [throttle](https://lodash.com/docs/4.17.15#throttle) value `useThrottle` accepts a value and a wait time in milliseconds, and returns a throttled version of that value. Unlike debouncing (which waits for idle), throttling ensures the value updates at most once per interval, providing a steady stream of updates. Under the hood it uses `lodash.throttle`, so you can pass the same options (`leading`, `trailing`) for fine-grained control. ### When to Use - Rate-limiting UI updates driven by high-frequency events (e.g., scroll position, resize dimensions) - Ensuring a value is emitted at regular intervals rather than waiting for a pause in changes - Providing steady visual feedback (e.g., progress indicators) from rapidly changing source values ### Notes - **Value-level throttle**: This hook throttles the *value* itself, not a callback. If you need to throttle a function invocation, use `useDebounceFn` with a `maxWait` option or a dedicated throttle utility. - **Options passthrough**: The third argument is forwarded directly to `lodash.throttle`, supporting `leading` and `trailing` edge configuration. - See also `useDebounce` for delaying updates until the value stops changing, which is better suited for search inputs and validation. ## Usage ```tsx live noInline function Demo() { const [value, setValue] = useState(); const throttledValue = useThrottle(value, 500); return (
setValue(e.target.value)} placeholder="Typed value" style={{ width: 280 }} />

throttledValue: {throttledValue}

); }; render(); ``` --- ## useToggle URL: https://reactuse.com/state/usetoggle/ Category: state Description: useToggle is a React hook to manage a boolean state with a toggle function — flip the value with no arguments or set it directly with true or false. Import: `import { useToggle } from '@reactuses/core'` # useToggle React state hook that tracks value of a boolean `useToggle` manages a boolean state value with a convenient toggle function. It returns a tuple containing the current boolean value and a toggle function. Calling `toggle()` with no arguments flips the value; calling `toggle(true)` or `toggle(false)` sets it directly. This provides a minimal API for the most common boolean state pattern. ### When to Use - Toggling UI elements like modals, dropdowns, sidebars, or accordions - Managing on/off states for features, dark mode, or settings - Controlling show/hide visibility of components with a simple tuple API ### Notes - **SSR-safe**: Works identically on server and client since it uses only React state. - **Flexible toggle**: The toggle function accepts an optional argument. Pass a boolean to set a specific value, or call with no arguments to flip. - See also `useBoolean` for a richer API with explicit `setTrue`/`setFalse` helpers, and `useDisclosure` for modal-style open/close patterns with callbacks. ## Usage ```tsx live function Demo() { const [on, toggle] = useToggle(true); return (
{on ? "ON" : "OFF"}
); }; ``` --- # Effect hooks (20) ## useAsyncEffect URL: https://reactuse.com/effect/useasynceffect/ Category: effect Description: useAsyncEffect is a React hook that brings async and await support to useEffect — run async effects with an optional async cleanup, safe against unmount. Import: `import { useAsyncEffect } from '@reactuses/core'` # useAsyncEffect React useEffect with async await support. Note it don't support generator function `useAsyncEffect` wraps React's `useEffect` to allow async/await syntax directly inside the effect callback. It accepts an async effect function, an optional async cleanup function, and a dependency list. The hook guards against state updates after unmount by checking the component's mounted status before running the effect. ### When to Use - Fetching data from an API on mount or when dependencies change, without needing a separate async IIFE inside `useEffect` - Running sequential asynchronous operations (e.g., reading from IndexedDB then updating state) with clean syntax - Performing async cleanup logic (e.g., closing a connection) when the component unmounts or deps change ### Notes - **No generator support**: Only `async` functions and plain functions are supported; generator functions are not handled. - **Unmount safety**: Internally uses `useMountedState` to skip execution if the component has already unmounted, preventing "state update on unmounted component" warnings. - The cleanup function runs synchronously when the effect re-fires or the component unmounts, matching standard `useEffect` cleanup behavior. ## Usage ```tsx live function Demo() { const [data, setData] = useState(0); useAsyncEffect( async () => { const result = await new Promise((resolve) => { setTimeout(() => { resolve(200); }, 5000); }); setData(result); }, () => {}, [], ); return
data: {data}
; }; ``` --- ## useCustomCompareEffect URL: https://reactuse.com/effect/usecustomcompareeffect/ Category: effect Description: useCustomCompareEffect is a React useEffect variant that re-runs based on a custom comparator instead of reference equality. Import: `import { useCustomCompareEffect } from '@reactuses/core'` # useCustomCompareEffect A modified useEffect hook that accepts a comparator which is used for comparison on dependencies instead of reference equality `useCustomCompareEffect` gives you full control over when an effect re-runs by letting you supply a custom comparison function for the dependency array. Instead of React's default reference equality check, the effect only fires when your comparator returns `false`. This is useful when dependencies are objects or arrays that are structurally equivalent but referentially different across renders. ### When to Use - Running an effect only when a specific property of a dependency object changes (e.g., an `id` field) while ignoring other property changes - Integrating with external data sources that produce new object references on every read but rarely change in meaningful ways - When `useDeepCompareEffect` is too broad and you need fine-grained comparison logic ### Notes - **Comparator signature**: The comparator receives `(prevDeps, nextDeps)` and should return `true` if they are considered equal (skip the effect), or `false` to re-run it. - **Return value**: Supports cleanup functions the same way as standard `useEffect`. - See also `useDeepCompareEffect` for automatic deep equality comparison without a custom comparator. ## Usage ```tsx live function Demo() { const [person, setPerson] = useState({ name: "bob", id: 1 }); const [count, setCount] = useState(0); useCustomCompareEffect( () => { setCount(c => c + 1); }, [person], (prevDeps, nextDeps) => prevDeps[0].id === nextDeps[0].id, ); return (

useCustomCompareEffect with deep comparison: {count}

); }; ``` --- ## useDebounceFn URL: https://reactuse.com/effect/usedebouncefn/ Category: effect Description: useDebounceFn is a React hook that wraps a function with debounce behavior — returns run, cancel, and flush controls, powered by lodash.debounce. Import: `import { useDebounceFn } from '@reactuses/core'` # useDebounceFn React hooks that [debounce](https://lodash.com/docs/4.17.15#debounce) function `useDebounceFn` wraps a function with debounce behavior powered by `lodash.debounce`. It returns an object with `run`, `cancel`, and `flush` methods, giving you full control over the debounced execution. The debounced function delays invoking your callback until after the specified wait time has elapsed since the last call. ### When to Use - Debouncing search input so API requests are only sent after the user stops typing - Limiting the rate of expensive computations triggered by rapidly changing values (e.g., window resize calculations) - Delaying form validation until the user pauses input ### Notes - **Lodash options**: The third parameter accepts `lodash.debounce` options such as `leading`, `trailing`, and `maxWait` for fine-tuned control. - **Cleanup**: Call `cancel()` to discard any pending debounced invocation, or `flush()` to execute it immediately. - See also `useThrottleFn` for rate-limiting that guarantees execution at regular intervals rather than waiting for inactivity. ## Usage ```tsx live function Demo() { const [value, setValue] = useState(0); const { run } = useDebounceFn(() => { setValue(value + 1); }, 500); return (

Clicked count: {value}

); }; ``` --- ## useDeepCompareEffect URL: https://reactuse.com/effect/usedeepcompareeffect/ Category: effect Description: useDeepCompareEffect is a React useEffect drop-in that deep-compares dependencies instead of reference equality — avoids needless effect runs on equal deps. Import: `import { useDeepCompareEffect } from '@reactuses/core'` # useDeepCompareEffect A modified useEffect hook that is using deep comparison on its dependencies instead of reference equality `useDeepCompareEffect` is a drop-in replacement for `useEffect` that performs deep structural comparison on the dependency array instead of shallow reference checks. This prevents unnecessary effect executions when dependencies are new object or array references that contain the same values. It has the same signature as `useEffect` and supports cleanup functions. ### When to Use - When your effect depends on objects or arrays that are re-created on every render (e.g., inline objects, API response data) - Avoiding infinite effect loops caused by non-memoized dependency references - When `useMemo` or `useCallback` on every dependency would be overly verbose ### Notes - **Performance**: Deep comparison has overhead proportional to the size of the dependency values. For large or deeply nested objects, consider `useCustomCompareEffect` with a targeted comparator instead. - **Cleanup support**: Supports return-based cleanup functions identically to `useEffect`. - See also `useCustomCompareEffect` when you need comparison logic beyond deep equality. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const effectCountRef = useRef(0); const deepCompareCountRef = useRef(0); useEffect(() => { effectCountRef.current += 1; // eslint-disable-next-line react-hooks/exhaustive-deps }, [{}]); useDeepCompareEffect(() => { deepCompareCountRef.current += 1; return () => { // do something }; }, [{}]); return (

effectCount: {effectCountRef.current}

deepCompareCount: {deepCompareCountRef.current}

); }; ``` --- ## useEvent URL: https://reactuse.com/effect/useevent/ Category: effect Description: useEvent is a React hook implementing the useEvent RFC — get an event handler with a stable identity that always calls the latest props and state. Import: `import { useEvent } from '@reactuses/core'` # useEvent Basic implementation of [React RFC useEvent](https://github.com/reactjs/rfcs/pull/220). It lets you define event handlers that can read the latest props/state but have always stable function identity `useEvent` returns a function with a stable reference that never changes between renders, while always calling through to the latest version of your callback. This is achieved by storing the callback in a ref that is updated on every render via `useIsomorphicLayoutEffect`. The returned function can safely be passed as a prop or dependency without causing unnecessary re-renders or effect re-runs. ### When to Use - Passing event handlers to memoized child components (`React.memo`) without breaking their memoization - Using a callback as a dependency in `useEffect` without triggering the effect on every render - Any scenario where you need a stable function identity that always reads the latest closure values ### Notes - **Stable identity**: The returned function reference is created once via `useCallback([], ...)` and never changes, making it safe to omit from dependency arrays. - **Layout-phase update**: The internal ref is updated during the layout phase (`useIsomorphicLayoutEffect`), ensuring the latest callback is available before any post-layout effects run. - In development mode, a console error is logged if the argument is not a function. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const callbackFn = useCallback(() => { alert(`Current count is ${count}`); }, [count]); const memoizedFn = useEvent(() => { alert(`Current count is ${count}`); }); return ( <>

count: {count}

); }; ``` --- ## useEventEmitter URL: https://reactuse.com/effect/useeventemitter/ Category: effect Description: useEventEmitter is a React hook that creates a lightweight publish and subscribe event system scoped to your component, stable across renders. Import: `import { useEventEmitter } from '@reactuses/core'` # useEventEmitter A basic eventemitter `useEventEmitter` creates a lightweight publish/subscribe event system scoped to your component. It returns a tuple of three items: an `event` function to register listeners (each returning a disposable), a `fire` function to broadcast a value to all listeners, and a `dispose` function to remove all listeners at once. Listener references are stored in a ref, so the emitter identity is stable across renders. ### When to Use - Coordinating communication between sibling components or decoupled modules without lifting state up - Building custom notification or messaging systems within a React tree - Implementing undo/redo or command patterns where multiple subscribers react to dispatched events ### Notes - **Disposable pattern**: Each call to the `event` function returns an object with a `dispose()` method, allowing you to remove individual listeners without affecting others. - **No automatic cleanup**: Listeners are not removed on unmount automatically. Call `dispose()` in a `useEffect` cleanup or use `useUnmount` to prevent memory leaks. - The emitter supports generic typing for both the event payload and an optional second argument. ## Usage ```tsx live noInline function Demo() { const [state, setState] = useState(0); const [event, fire, dispose] = useEventEmitter(); const event1 = useRef(); useEffect(() => { event((val) => { setState(s => s + val); }); event1.current = event(val => setState(s => s + val + 10)); }, [event]); return (
state: {state}
); }; render(); ``` --- ## useEventListener URL: https://reactuse.com/effect/useeventlistener/ Category: effect Description: useEventListener is a React hook to attach a DOM event listener to an element, window, or document with automatic cleanup and an always-current handler. Import: `import { useEventListener } from '@reactuses/core'` # useEventListener Use EventListener with ease. `useEventListener` attaches a DOM event listener to a target element (or `window`/`document`) and automatically removes it on unmount or when dependencies change. It accepts the event name, handler function, and an optional target ref or element. The handler is always up-to-date without needing to re-register the listener, thanks to an internal ref via `useLatest`. ### When to Use - Listening for keyboard shortcuts, mouse clicks, or scroll events on specific elements - Attaching `resize`, `visibilitychange`, or `storage` events to `window`/`document` - Any case where you need automatic cleanup of event listeners tied to component lifecycle ### Notes - **SSR-safe**: Skips listener registration during server-side rendering since `window`/`document` are unavailable. - **Stable handler**: Uses `useLatest` internally so the handler always points to the latest closure without re-attaching the listener. - The third argument defaults to `window` and accepts a raw element, a ref object, or a function returning an element. See also `useEvent` for a stable callback ref pattern, and `useDebounceFn`/`useThrottleFn` for rate-limited event handling. ## Usage ```tsx live function Demo() { const buttonRef = useRef(null); const [state, setState] = useState("NO DB Click"); const onDBClick = () => { setState("DB Clicked"); }; const onClick = (event: Event) => { console.log("button clicked!", event); }; const onVisibilityChange = (event: Event) => { console.log("doc visibility changed!", { isVisible: !document.hidden, event, }); }; // example with window based event useEventListener("dblclick", onDBClick); // example with document based event useEventListener("visibilitychange", onVisibilityChange, () => document); // example with element based event useEventListener("click", onClick, buttonRef); return (

{state}

); }; ``` --- ## useInterval URL: https://reactuse.com/effect/useinterval/ Category: effect Description: useInterval is a React hook for a declarative setInterval — pass a callback and a delay (or null to pause), with isActive, pause, and resume controls. Import: `import { useInterval } from '@reactuses/core'` # useInterval A declarative interval hook based on [Dan Abramov's article on overreacted.io](https://overreacted.io/making-setinterval-declarative-with-react-hooks/). The interval can be paused by setting the delay to null You can also manually control it by passing the `controls` parameter. `useInterval` wraps `setInterval` in a declarative React API. It takes a callback, a delay in milliseconds (or `null` to pause), and an optional options object. It returns a `Pausable` object with `isActive`, `pause`, and `resume` methods for manual control. The callback always references the latest closure without resetting the interval. ### When to Use - Building countdown timers, clocks, or polling mechanisms that tick at a regular interval - Auto-refreshing data from an API at a fixed cadence - Animating values over time with a consistent step interval ### Notes - **Pause/resume**: Set `delay` to `null` to pause the interval, or use the returned `pause()`/`resume()` methods for imperative control. - **Immediate option**: Pass `{ immediate: true }` to execute the callback immediately on start in addition to after each interval. - The interval is automatically cleared on component unmount. See also `useTimeout` for single-fire delayed execution and `useRafFn` for frame-based animation loops. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); useInterval(() => { setCount(count + 1); }, 1000); return
count: {count}
; }; ``` --- ## useIsomorphicLayoutEffect URL: https://reactuse.com/effect/useisomorphiclayouteffect/ Category: effect Description: useIsomorphicLayoutEffect is a React hook that uses useLayoutEffect in the browser and useEffect on the server — avoids the SSR useLayoutEffect warning. Import: `import { useIsomorphicLayoutEffect } from '@reactuses/core'` # useIsomorphicLayoutEffect `useIsomorphicLayoutEffect` that does not show warning when server-side rendering, see [Alex Reardon's article](https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a) for more info `useIsomorphicLayoutEffect` resolves to `useLayoutEffect` in browser environments and `useEffect` on the server. This eliminates the React warning about `useLayoutEffect` doing nothing during SSR while preserving synchronous DOM measurement behavior in the client. It has the exact same signature as `useEffect`/`useLayoutEffect`, making it a drop-in replacement. ### When to Use - Measuring or mutating the DOM synchronously before the browser paints, in projects that also support server-side rendering - Building library hooks that need layout-phase timing but must work in SSR frameworks (Next.js, Remix, etc.) - Any place you would use `useLayoutEffect` but need to avoid SSR console warnings ### Notes - **Environment detection**: Uses a simple `isBrowser` check (typeof `window` !== `undefined`) to select the appropriate hook. - **Same API**: Accepts an effect callback and optional dependency array, identical to both `useEffect` and `useLayoutEffect`. - This hook is used internally by several other hooks in this library (e.g., `useEvent`) to ensure SSR compatibility. ## Usage ```tsx live function Demo() { const [value] = useState("useIsomorphicLayoutEffect"); useIsomorphicLayoutEffect(() => { window.console.log(value); }, [value]); return
{value}
; }; ``` --- ## useMount URL: https://reactuse.com/effect/usemount/ Category: effect Description: useMount is a React lifecycle hook that runs a callback exactly once after the component mounts — a clear alternative to useEffect with empty deps. Import: `import { useMount } from '@reactuses/core'` # useMount React lifecycle hook that executes a function after the component is mounted `useMount` runs a callback exactly once after the component mounts, equivalent to `useEffect(() => { ... }, [])`. It provides a semantically clear way to express mount-only logic without manually specifying an empty dependency array. The callback receives no arguments and does not support a return-based cleanup function. ### When to Use - Running one-time initialization logic such as analytics tracking, logging, or third-party SDK setup - Performing DOM measurements or imperative focus calls immediately after the component first renders - Replacing class component `componentDidMount` behavior with a concise hook ### Notes - **No cleanup**: `useMount` does not support a cleanup return value. If you need unmount cleanup, pair it with `useUnmount` or use `useEffect` directly. - **Development validation**: In development mode, a console error is logged if the provided argument is not a function. - See also `useUnmount` for the corresponding unmount lifecycle, and `useOnceEffect` if you need React 18 Strict Mode double-invoke protection. ## Usage ```tsx live function Demo() { const [value, setValue] = useState("UnMounted"); useMount(() => { setValue("Mounted"); }); return
{value}
; }; ``` --- ## useOnceEffect URL: https://reactuse.com/effect/useonceeffect/ Category: effect Description: useOnceEffect is a React useEffect variant that runs the effect only once, even under React 18 Strict Mode's double-invocation in development. Import: `import { useOnceEffect } from '@reactuses/core'` # useOnceEffect A Hook that avoids React18 useEffect run twice `useOnceEffect` is a variant of `useEffect` that guarantees the effect callback executes only once, even under React 18's Strict Mode which intentionally double-invokes effects during development. It uses a `WeakSet`-based tracking mechanism to detect and skip duplicate invocations. The API is identical to `useEffect` -- it accepts an effect callback and an optional dependency array. ### When to Use - Performing side effects that must run exactly once (e.g., sending an analytics event, initializing a third-party library) and cannot tolerate React 18 Strict Mode double-firing - Protecting against duplicate API calls on mount in development mode with `` enabled - Replacing manual `useRef`-based "already ran" guards with a cleaner API ### Notes - **React 18 Strict Mode**: In development, React 18 mounts, unmounts, and re-mounts components to surface impure effects. `useOnceEffect` prevents the second invocation by tracking the effect reference in a `WeakSet`. - **Production behavior**: In production builds where Strict Mode double-invocation does not occur, `useOnceEffect` behaves identically to `useEffect`. - See also `useOnceLayoutEffect` for the same behavior using `useLayoutEffect` timing, and `useMount` for a simpler mount-only callback. ## Usage ```tsx live function Demo() { const [effect, setEffect] = useState(0); const [onceEffect, setOnceEffect] = useState(0); useOnceEffect(() => { setOnceEffect(onceEffect => onceEffect + 1); }, []); useEffect(() => { setEffect(effect => effect + 1); }, []); return (
onceEffect: {onceEffect}

effect: {effect}
); }; ``` --- ## useOnceLayoutEffect URL: https://reactuse.com/effect/useoncelayouteffect/ Category: effect Description: useOnceLayoutEffect is a React useLayoutEffect variant that runs only once, even under React 18 Strict Mode's double-invocation — synchronous before paint. Import: `import { useOnceLayoutEffect } from '@reactuses/core'` # useOnceLayoutEffect A Hook that avoids React18 useLayoutEffect run twice `useOnceLayoutEffect` is a variant of `useLayoutEffect` that guarantees the effect callback executes only once, even under React 18's Strict Mode which intentionally double-invokes effects during development. It uses the same `WeakSet`-based tracking mechanism as `useOnceEffect` but runs with `useLayoutEffect` timing -- synchronously after DOM mutations and before the browser paints. ### When to Use - Performing DOM measurements or mutations that must happen exactly once before paint, without being duplicated by React 18 Strict Mode - Initializing layout-dependent third-party libraries (e.g., chart or animation libraries that manipulate the DOM directly) that break when initialized twice - Any case where you need `useLayoutEffect` semantics with guaranteed single-execution ### Notes - **Layout timing**: Runs synchronously after all DOM mutations, before the browser repaints. This can block visual updates if the effect is slow. - **React 18 Strict Mode**: Prevents the double-invocation that React 18 performs in development to help detect side-effect issues. - See also `useOnceEffect` for the `useEffect`-timed equivalent, and `useIsomorphicLayoutEffect` for SSR-safe layout effects. ## Usage ```tsx live function Demo() { const [updateEffect, setLayoutEffect] = useState(0); const [onceLayoutEffect, setOnceLayoutEffect] = useState(0); useOnceLayoutEffect(() => { setOnceLayoutEffect(onceEffect => onceEffect + 1); }, []); useLayoutEffect(() => { setLayoutEffect(effect => effect + 1); }, []); return (
onceEffect: {onceLayoutEffect}

effect: {updateEffect}
); }; ``` --- ## useRafFn URL: https://reactuse.com/effect/useraffn/ Category: effect Description: useRafFn is a React hook that runs a callback on every requestAnimationFrame tick with a timestamp, plus stop, start, and isActive controls. Import: `import { useRafFn } from '@reactuses/core'` # useRafFn Call function on every [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame). With controls of pausing and resuming `useRafFn` schedules a callback to run on every `requestAnimationFrame` tick, providing a high-resolution timestamp to the callback on each frame. It returns a tuple of `[stop, start, isActive]` for full imperative control over the animation loop. The callback reference is kept up-to-date via `useLatest`, so you always access the latest closure values without restarting the loop. ### When to Use - Building smooth animations that need to update on every browser paint frame (e.g., canvas drawing, CSS transforms) - Implementing real-time visualizations like FPS counters, progress indicators, or physics simulations - Running continuous visual updates that should pause and resume based on user interaction or visibility ### Notes - **Auto-start**: By default the loop starts immediately on mount. Pass `false` as the second argument to start in a paused state. - **Cleanup**: The animation frame is automatically cancelled on unmount via the effect cleanup. - See also `useInterval` for fixed-interval timing and `useUpdate` for triggering a single re-render on demand. ## Usage ```tsx live function Demo() { const [ticks, setTicks] = useState(0); const [lastCall, setLastCall] = useState(0); const update = useUpdate(); const [loopStop, loopStart, isActive] = useRafFn((time) => { setTicks(ticks => ticks + 1); setLastCall(time); }); return (
RAF triggered: {ticks} (times)
Last high res timestamp: {lastCall}

); }; ``` --- ## useThrottleFn URL: https://reactuse.com/effect/usethrottlefn/ Category: effect Description: useThrottleFn is a React hook that wraps a function with throttle behavior — runs at most once per interval, with run, cancel, and flush controls. Import: `import { useThrottleFn } from '@reactuses/core'` # useThrottleFn React hooks that [throttle](https://lodash.com/docs/4.17.15#throttle) function `useThrottleFn` wraps a function with throttle behavior powered by `lodash.throttle`. It returns an object with `run`, `cancel`, and `flush` methods. Unlike debounce, throttle guarantees that the function executes at most once per specified time interval, making it ideal for rate-limiting high-frequency events while still providing periodic updates. ### When to Use - Rate-limiting scroll or mousemove event handlers to maintain smooth performance without dropping all intermediate calls - Ensuring a save or sync operation runs at regular intervals during continuous user input - Throttling resize handlers to limit layout recalculations while still responding periodically ### Notes - **Lodash options**: The third parameter accepts `lodash.throttle` options such as `leading` and `trailing` to control whether the function fires at the start, end, or both edges of the throttle window. - **Cleanup**: Call `cancel()` to discard any pending throttled invocation, or `flush()` to execute it immediately. - See also `useDebounceFn` for delaying execution until after a pause in activity, which is better suited for search-as-you-type patterns. ## Usage ```tsx live function Demo() { const [value, setValue] = useState(0); const { run } = useThrottleFn(() => { setValue(value + 1); }, 500); return (

Clicked count: {value}

); }; ``` --- ## useTimeout URL: https://reactuse.com/effect/usetimeout/ Category: effect Description: useTimeout is a React hook that provides a pending state which flips to false after a delay — returns isPending plus start and cancel controls. Import: `import { useTimeout } from '@reactuses/core'` # useTimeout Update value after a given time `useTimeout` provides a reactive pending state that flips from `true` to `false` after a specified delay. It returns a tuple of `[isPending, start, cancel]`, giving you both a declarative status value and imperative controls. By default, the timer starts immediately on mount, but you can configure it to start manually via the `immediate` option. ### When to Use - Showing a loading indicator or splash screen for a minimum duration before revealing content - Implementing auto-dismiss behavior for notifications, toasts, or banners after a fixed time - Creating timed UI state transitions (e.g., disabling a button for a cooldown period) ### Notes - **Immediate by default**: The timer starts automatically on mount. Pass `{ immediate: false }` to require an explicit `start()` call. - **Restartable**: Calling `start()` resets and restarts the timer. Calling `cancel()` stops it and keeps `isPending` at its current value. - See also `useTimeoutFn` for executing a callback after a delay instead of toggling a boolean state, and `useInterval` for repeated execution. ## Usage ```tsx live function Demo() { const [isPending, start, cancel] = useTimeout(5000); return (
Pending: {JSON.stringify(isPending)}
); }; ``` --- ## useTimeoutFn URL: https://reactuse.com/effect/usetimeoutfn/ Category: effect Description: useTimeoutFn is a React hook that wraps setTimeout with a React-friendly API — runs a callback after a delay, with isPending, start, and cancel controls. Import: `import { useTimeoutFn } from '@reactuses/core'` # useTimeoutFn Wrapper for setTimeout with controls `useTimeoutFn` wraps `setTimeout` with a React-friendly API, executing a callback after a specified delay. It returns a tuple of `[isPending, start, cancel]` for full control over the timeout lifecycle. The callback reference stays current so you always execute the latest closure values when the timer fires. ### When to Use - Delaying a side effect (e.g., showing a tooltip, triggering a redirect) by a fixed duration after a user action - Implementing retry logic with a delay between attempts - Deferring expensive operations to run after a brief pause (e.g., lazy-loading content after a transition) ### Notes - **Immediate by default**: The timer starts on mount unless you pass `{ immediate: false }`, which requires calling `start()` manually. - **Restartable**: Calling `start()` cancels any in-flight timeout and starts a new one. Calling `cancel()` stops the pending timeout. - See also `useTimeout` for a simpler boolean-state variant, and `useDebounceFn` for delaying execution until input activity stops. ## Usage ```tsx live function Demo() { const [text, setText] = useState("Please wait for 3 seconds"); const [isPending, start] = useTimeoutFn( () => { setText("Fired!"); }, 3000, { immediate: false }, ); return (

{text}

); }; ``` --- ## useUnmount URL: https://reactuse.com/effect/useunmount/ Category: effect Description: useUnmount is a React lifecycle hook that runs a cleanup function once when the component unmounts, with access to the latest props and state. Import: `import { useUnmount } from '@reactuses/core'` # useUnmount React lifecycle hook that calls a function when the component will unmount `useUnmount` runs a cleanup function exactly once when the component unmounts. It stores the callback in a ref via `useLatest`, ensuring the function always has access to the latest props and state at the time of unmount -- without needing to list them as dependencies. This avoids the stale closure problem common with plain `useEffect` cleanup. ### When to Use - Cleaning up subscriptions, WebSocket connections, or event listeners when a component is removed from the tree - Cancelling in-flight network requests or aborting async operations on unmount - Logging or analytics tracking when a user navigates away from a page or closes a modal ### Notes - **Latest closure**: Unlike a bare `useEffect` cleanup, the callback always sees the most recent state and props because it reads from a ref. - **Development validation**: In development mode, a console error is logged if the provided argument is not a function. - See also `useMount` for the corresponding mount lifecycle hook. ## Usage ```tsx live function Demo() { const [value] = useState("mounted"); useUnmount(() => { alert("UnMounted"); }); return
{value}
; }; ``` --- ## useUpdate URL: https://reactuse.com/effect/useupdate/ Category: effect Description: useUpdate is a React hook that returns a stable function to force a component re-render when called — useful for imperative refresh scenarios. Import: `import { useUpdate } from '@reactuses/core'` # useUpdate React utility hook that returns a function that forces component to re-render when called `useUpdate` returns a stable function that forces the component to re-render when invoked. Internally it uses `useReducer` with an incrementing counter, so each call produces a new state value that triggers React's reconciliation. The returned function identity is stable across renders, making it safe to pass as a prop or store in a ref. ### When to Use - Forcing a re-render after mutating a ref or external mutable value that React does not track - Integrating with imperative APIs or third-party libraries that update state outside of React's awareness - Refreshing displayed values (e.g., `Date.now()`) on demand without managing explicit state ### Notes - **Stable identity**: The returned update function never changes between renders, so it can safely be used in dependency arrays or passed to child components. - **Use sparingly**: Forcing re-renders bypasses React's declarative model. Prefer state or context updates when possible. - See also `useRafFn` for continuous re-rendering on every animation frame. ## Usage ```tsx live function Demo() { const update = useUpdate(); return ( <> {/* to avoid ssr error beacause date.now() will not be same in server and client */}
Time: {Date.now()}
); }; ``` --- ## useUpdateEffect URL: https://reactuse.com/effect/useupdateeffect/ Category: effect Description: useUpdateEffect is a React useEffect variant that skips the initial mount run — the effect fires only on subsequent dependency changes. Import: `import { useUpdateEffect } from '@reactuses/core'` # useUpdateEffect React effect hook that ignores the first invocation (e.g. on mount). The signature is exactly the same as the `useEffect` hook `useUpdateEffect` works identically to `useEffect` except that it skips the initial execution on mount. The effect only fires on subsequent dependency changes, making it useful when you want to react to updates but not to the initial render. It uses `useFirstMountState` internally to detect and skip the first invocation. ### When to Use - Running a side effect only when a value changes after the initial render (e.g., syncing a form field to an API only on updates, not on mount) - Showing a "value changed" notification without triggering it when the component first appears - Skipping initial data fetches when the component already has default or cached data ### Notes - **Same signature**: Accepts an effect callback and optional dependency array, identical to `useEffect`. Supports cleanup functions via the return value. - **First-mount detection**: Uses `useFirstMountState` internally, which tracks mount status via a ref. - See also `useUpdateLayoutEffect` for the same skip-first-run behavior using `useLayoutEffect` timing, and `useDeepCompareEffect` for deep dependency comparison. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const [effectCount, setEffectCount] = useState(0); const [updateEffectCount, setUpdateEffectCount] = useState(0); useEffect(() => { setEffectCount(c => c + 1); }, [count]); useUpdateEffect(() => { setUpdateEffectCount(c => c + 1); return () => { // do something }; }, [count]); // you can include deps array if necessary return (

effectCount: {effectCount}

updateEffectCount: {updateEffectCount}

); }; ``` --- ## useUpdateLayoutEffect URL: https://reactuse.com/effect/useupdatelayouteffect/ Category: effect Description: useUpdateLayoutEffect is a React useLayoutEffect variant that skips the initial mount run — fires synchronously after DOM mutations on later changes. Import: `import { useUpdateLayoutEffect } from '@reactuses/core'` # useUpdateLayoutEffect React layoutEffect hook that ignores the first invocation (e.g. on mount). The signature is exactly the same as the `useLayoutEffect` hook `useUpdateLayoutEffect` works identically to `useLayoutEffect` except that it skips the initial execution on mount. The effect fires synchronously after DOM mutations but only on subsequent dependency changes, not on the first render. This is useful for DOM measurements or mutations that should only respond to updates. ### When to Use - Adjusting layout or scroll position in response to state changes, but not on the initial render when the DOM is first painted - Synchronously updating DOM attributes or styles only when a dependency has actually changed after mount - Preventing initial flash-of-content issues when a layout effect would incorrectly run its update logic on mount ### Notes - **Layout timing**: Runs synchronously after DOM mutations and before the browser repaints, the same as `useLayoutEffect`. Avoid slow operations to prevent blocking visual updates. - **Same signature**: Accepts an effect callback and optional dependency array, identical to `useLayoutEffect`. Supports cleanup functions via the return value. - See also `useUpdateEffect` for the `useEffect`-timed equivalent, and `useIsomorphicLayoutEffect` for SSR-safe layout effects. ## Usage ```tsx live function Demo() { const [count, setCount] = useState(0); const [layoutEffectCount, setLayoutEffectCount] = useState(0); const [updateLayoutEffectCount, setUpdateLayoutEffectCount] = useState(0); useLayoutEffect(() => { setLayoutEffectCount(c => c + 1); }, [count]); useUpdateLayoutEffect(() => { setUpdateLayoutEffectCount(c => c + 1); return () => { // do something }; }, [count]); // you can include deps array if necessary return (

layoutEffectCount: {layoutEffectCount}

updateLayoutEffectCount: {updateLayoutEffectCount}

); }; ``` --- # Element hooks (19) ## useActiveElement URL: https://reactuse.com/element/useactiveelement/ Category: element Description: useActiveElement is a React hook that reactively tracks document.activeElement — returns the focused DOM element, or null, updating on focus and blur. Import: `import { useActiveElement } from '@reactuses/core'` # useActiveElement React Sensor Hooks that tracks document.activeElement `useActiveElement` reactively tracks which DOM element currently has focus via [`document.activeElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement). It returns the focused element (typed with a generic parameter) or `null` when no element is focused. The hook automatically listens for `focus` and `blur` events on the document to keep the value up to date. ### When to Use - Highlighting or styling the currently focused input in a form - Building accessibility tools or focus-trap components that need to know which element has focus - Debugging focus flow in complex UIs with many interactive elements ### Notes - **SSR-safe**: Returns `null` during server-side rendering since `document` is not available. - **Generic type**: You can narrow the return type with a type parameter, e.g. `useActiveElement()`, to get typed access to element properties like `dataset`. - See also `useFocus` for controlling and tracking focus state on a specific element. ## Usage ```tsx live noInline function Demo() { const arr = [1, 2, 3, 4, 5, 6]; const activeElement = useActiveElement(); const key = useMemo(() => { return activeElement?.dataset?.id; }, [activeElement?.dataset?.id]); return (

Select the inputs below to see the changes

{arr.map((i) => { return ; })}

Current Active Element: {activeElement?.tagName}
Current Active Element data-key: {key}
); }; render(); ``` --- ## useClickAway URL: https://reactuse.com/element/useclickaway/ Category: element Description: useClickAway is a React hook to detect clicks outside an element — an alias for useClickOutside. Ideal for closing modals, dropdowns, and popovers. Import: `import { useClickAway } from '@reactuses/core'` # useClickAway Listen for clicks outside of an element. Useful for modal or dropdown. :::info `useClickAway` is an alias for [`useClickOutside`](/element/useclickoutside). They have identical functionality and API. ::: `useClickAway` detects clicks (mouse and touch events) that occur outside of a referenced DOM element and invokes a callback when they happen. Pass a ref to the element you want to protect and a handler function. You can also pass an `enabled` flag to conditionally activate or deactivate the listener. ### When to Use - Closing dropdown menus, popovers, or modals when the user clicks outside of them - Deselecting or deactivating an inline editing component when focus moves away - Dismissing notification toasts or context menus on outside interaction ### Notes - **Event types**: Listens for both `mousedown` and `touchstart` events, covering desktop and mobile interactions. - **Cleanup**: The event listeners are automatically removed when the component unmounts or when `enabled` is set to `false`. - This hook is an alias for `useClickOutside`. Use whichever name you prefer -- they share the same implementation. ## Usage ```tsx live function Demo() { const [visible, setVisible] = useState(false); const modalRef = useRef(null); useClickAway(modalRef, () => { setVisible(false); }); return (
{visible && (

Demo Modal

Click outside of the modal to close it.

)}
); }; ``` --- ## useClickOutside URL: https://reactuse.com/element/useclickoutside/ Category: element Description: useClickOutside is a React hook that detects mouse and touch clicks outside a referenced element and fires a callback — ideal for modals and dropdowns. Import: `import { useClickOutside } from '@reactuses/core'` # useClickOutside Listen for clicks outside of an element. Useful for modal or dropdown `useClickOutside` detects clicks (mouse and touch events) that occur outside of a referenced DOM element and invokes a callback when they happen. Pass a ref to the target element, a handler function, and an optional `enabled` boolean to conditionally toggle the listener. The handler receives the original `MouseEvent` or `TouchEvent`. ### When to Use - Closing dropdown menus, popovers, or modals when the user clicks outside of them - Deselecting or deactivating an inline editing component when focus moves away - Dismissing notification toasts or context menus on outside interaction ### Notes - **Event types**: Listens for both `mousedown` and `touchstart` events, covering desktop and mobile interactions. - **Cleanup**: The event listeners are automatically removed when the component unmounts or when `enabled` is set to `false`. - Also available as `useClickAway`, which is an alias with the identical API and implementation. ## Usage ```tsx live function Demo() { const [visible, setVisible] = useState(false); const modalRef = useRef(null); useClickOutside(modalRef, () => { setVisible(false); }); return (
{visible && (

Demo Modal

Click outside of the modal to close it.

)}
); }; ``` --- ## useDocumentVisibility URL: https://reactuse.com/element/usedocumentvisibility/ Category: element Description: useDocumentVisibility is a React hook that reactively tracks page visibility via the Page Visibility API — returns visible or hidden as the user switches tabs. Import: `import { useDocumentVisibility } from '@reactuses/core'` # useDocumentVisibility React Sensor Hook that tracks [document.visibilityState](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) `useDocumentVisibility` reactively tracks whether the page is visible or hidden using the [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API). It returns the current `DocumentVisibilityState` (`"visible"` or `"hidden"`) and updates automatically when the user switches tabs or minimizes the browser. You can provide a default value for the initial state. ### When to Use - Pausing animations, videos, or timers when the user navigates away from the tab - Showing a "welcome back" message or refreshing stale data when the user returns - Reducing network requests or resource consumption while the page is in the background ### Notes - **SSR-safe**: Accepts a `defaultValue` parameter (e.g. `"hidden"`) that is used during server-side rendering when `document` is not available. - **Lightweight**: Listens to the `visibilitychange` event on `document` and cleans up the listener on unmount. - See also `useWindowFocus` for tracking whether the browser window itself has focus (vs. just tab visibility). ## Usage ```tsx live function Demo() { const visibility = useDocumentVisibility("hidden"); const [message, setMessage] = useState( "💡 Minimize the page or switch tab then return", ); useEffect(() => { if (visibility === "visible") { setTimeout(() => { setMessage("🎉 Welcome back!"); }, 2000); } else { setTimeout(() => { setMessage("🥰 Take a break"); }, 2000); } }, [visibility]); return
{message}
; }; ``` --- ## useDoubleClick URL: https://reactuse.com/element/usedoubleclick/ Category: element Description: useDoubleClick is a React hook that distinguishes single-click from double-click on an element using a configurable latency, with separate handlers. Import: `import { useDoubleClick } from '@reactuses/core'` # useDoubleClick React sensor hook that controls double click and single click `useDoubleClick` lets you distinguish between single-click and double-click interactions on a DOM element. It uses a configurable latency delay to determine whether a click is a single click or the first click of a double-click sequence. Pass a target ref and provide separate `onSingleClick` and `onDoubleClick` handlers to respond to each interaction. ### When to Use - Implementing "click to select, double-click to edit" patterns on list items or table cells - Adding double-click-to-zoom on images or maps while preserving single-click for other actions - Any UI where single and double clicks must trigger distinct behaviors on the same element ### Notes - **Latency**: The default delay between single and double click detection can be customized via the `latency` option (in milliseconds). A shorter latency makes single clicks feel faster but may miss slower double clicks. - **Event types**: Supports both mouse and touch events, making it suitable for desktop and mobile. - **Cleanup**: All event listeners are removed automatically when the component unmounts. ## Usage ```tsx live function Demo() { const element = useRef(null); const [text, setText] = useState("no click"); useDoubleClick({ target: element, onSingleClick: () => { setText("single click"); }, onDoubleClick: () => { setText("double click"); }, }); return (

{text}

); }; ``` --- ## useDraggable URL: https://reactuse.com/element/usedraggable/ Category: element Description: useDraggable is a React hook that makes any HTML or SVG element draggable — tracks pointer, mouse, and touch input, returning x and y position. Import: `import { useDraggable } from '@reactuses/core'` # useDraggable Make elements draggable `useDraggable` makes any HTML or SVG element draggable by tracking pointer events and returning the current `x` and `y` position, a boolean indicating whether the element is being dragged, and a function to programmatically set the position. It supports pointer, mouse, touch, and pen inputs, and can optionally constrain movement within a container element. ### When to Use - Building draggable panels, floating toolbars, or resizable widgets - Implementing drag-to-reposition functionality for dashboard cards or kanban items - Creating interactive diagrams or editors where elements need free movement ### Notes - **Touch support**: Set `touch-action: none` on the draggable element's CSS to prevent browser scroll interference on touch devices. - **Container bounds**: Use the `containerElement` option to restrict dragging within a parent element. The hook will calculate bounds automatically. - **Callbacks**: The `onStart`, `onMove`, and `onEnd` callbacks give you fine-grained control. Returning `false` from `onStart` prevents the drag from beginning. - **Cleanup**: All pointer event listeners are removed automatically on unmount. ## Usage ### Fixed Demo ```tsx live function Demo() { const el = useRef(null); const [initialValue, setInitialValue] = useState({ x: 200 / 2.2, y: 120 }); useEffect(() => { setInitialValue({ x: window.innerWidth / 2.2, y: 120 }); }, []); const [x, y, isDragging] = useDraggable(el, { initialValue, preventDefault: true, }); return (

Check the floating boxes

{isDragging ? "Dragging!" : "👋 Drag me!"}
I am at {Math.round(x)}, {Math.round(y)}
); }; ``` ### Relative Demo ```tsx live function Demo() { const el = useRef(null); const scope = useRef(null); const initialValue = { x: 200 / 2.2, y: 120 }; const [x, y, isDragging, setPosition] = useDraggable(el, { initialValue, preventDefault: true, containerElement: scope, }); return (
{isDragging ? "Dragging!" : "👋 Drag me!"}
I am at {Math.round(x)}, {Math.round(y)}
); }; ``` --- ## useDropZone URL: https://reactuse.com/element/usedropzone/ Category: element Description: useDropZone is a React hook that turns an element into a file drop zone — handles drag events and returns an over-zone boolean, with a dropped-files callback. Import: `import { useDropZone } from '@reactuses/core'` # useDropZone Create an zone where files can be dropped `useDropZone` turns a DOM element into a file drop target by handling the `dragenter`, `dragover`, `dragleave`, and `drop` events. It returns a boolean indicating whether a file is currently being dragged over the zone. When files are dropped, the provided callback receives an array of `File` objects (or `null` if no files were dropped). ### When to Use - Building file upload interfaces where users drag and drop files from their desktop - Creating media galleries or document managers with drag-and-drop support - Implementing drag-and-drop zones in form builders or CMS editors ### Notes - **Visual feedback**: Use the returned `isOver` boolean to highlight the drop zone (e.g., change border color or background) when a file is dragged over it. - **Cleanup**: All drag-related event listeners are removed automatically when the component unmounts. - See also `useDraggable` for making elements draggable within the page (element repositioning vs. file drops). ## Usage ```tsx live function Demo() { const ref = useRef(null); const isOver = useDropZone(ref, (_files) => {}); return (

Drop files into dropZone

{/* */}
isOverDropZone: {JSON.stringify(isOver)}
); }; ``` --- ## useElementBounding URL: https://reactuse.com/element/useelementbounding/ Category: element Description: useElementBounding is a React hook that reactively tracks an element's getBoundingClientRect — x, y, width, height, and edges, updating on scroll and resize. Import: `import { useElementBounding } from '@reactuses/core'` # useElementBounding React Element Hook that tracks bounding box of an HTML element `useElementBounding` reactively tracks the bounding rectangle of a DOM element using [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). It returns an object containing `x`, `y`, `top`, `bottom`, `left`, `right`, `width`, `height`, and an `update()` function for manual re-measurement. By default it automatically recalculates on window scroll and resize. ### When to Use - Positioning tooltips, popovers, or floating elements relative to a target element - Implementing collision detection or overlap checks between UI elements - Tracking element position for scroll-linked animations or parallax effects ### Notes - **Reactivity**: Automatically updates on window `resize` and `scroll` events by default. Both behaviors can be disabled via `windowResize` and `windowScroll` options. - **SSR-safe**: Returns zero values during server-side rendering. Set `immediate: false` to defer the first measurement until you explicitly call `update()`. - See also `useElementSize` and `useMeasure` for tracking only width/height via ResizeObserver, and `useWindowSize` for viewport dimensions. ## Usage ```tsx live function Demo() { const ref = useRef(null); const rect = useElementBounding(ref); return (

Resize the box to see changes