ReactUse Documentation

repository·main·Indexed 21 days ago

https://github.com/childrentime/reactuse

A comprehensive collection of over 100 production-ready React hooks for browser APIs, state management, DOM manipulation, and side effects. Includes documentation on using @reactuses/core, MCP support for AI-powered hook discovery, and tools like ts-document for generating documentation from TypeScript interfaces.

Tokens
452.7K
Snippets
1K
Records
1.4K
Agent score
70%

What's inside ReactUse

  1. What is ReactUse

    main

    ReactUse is an open-source collection of over 110 production-ready React Hooks. It is designed to reduce boilerplate by providing TypeScript-first, tree-shakable, and SSR-compatible hooks. The library brings ergonomic patterns (inspired by VueUse) to the React ecosystem, covering areas such as:

    • Browser APIs
    • State management
    • DOM observation
    • Side effects
    • Third-party integrations

    ReactUse is released under the Unlicense, meaning it is free for both personal and commercial use without restrictions.

  2. ReactUse compatibility and features

    main

    ReactUse is designed for modern React development with the following characteristics:

    • SSR Compatibility: Works with Next.js (App Router and Pages Router), Remix, Gatsby, and other SSR frameworks.
    • React Version Support: Supports React 16.8 through React 19.
    • TypeScript Support: Full type definitions and generics support.
    • Tree-Shakable: Unused hooks are eliminated at build time.
    • License: Released under the Unlicense (free for personal and commercial use).
  3. Explore ReactUse State Management Hooks

    main

    ReactUse provides a suite of specialized hooks for managing complex state patterns that go beyond the standard useState. Key state-related hooks include:

    • useControlled: Build components that support both controlled and uncontrolled modes.
    • usePrevious: Access the value from the previous render cycle.
    • useDebounce: Debounce any value by a specified delay.
    • useThrottle: Throttle any value to update at most once per interval.
    • useCycleList: Cycle through an array of values using next/prev functions.
    • useCounter: Manage numeric state with inc/dec/reset and optional min/max constraints.
    • useSetState: Merge partial objects into state, mimicking the behavior of class-component setState.
    • useBoolean: Manage boolean state with toggle, setTrue, and setFalse helpers.
    • useToggle: Toggle between two specific values.
    • useLocalStorage: Persist state to localStorage with automatic serialization.
  4. Optimizing Background Tabs

    main

    To reduce unnecessary computation, network requests, or animations when a user is not interacting with your app, use visibility hooks:

    • useDocumentVisibility: Returns whether the document is "visible" or "hidden". Use this to pause polling or heavy background tasks.
    • useWindowFocus: Tracks if the browser window itself has focus. This is useful for throttling tasks when the tab is visible but the user is interacting with another window or DevTools.
    import { useDocumentVisibility } from "@reactuses/core";
    import { useEffect, useState } from "react";
    
    function usePolling(url: string, intervalMs: number) {
      const visibility = useDocumentVisibility();
      const [data, setData] = useState(null);
    
      useEffect(() => {
        if (visibility === "hidden") return; // stop polling in background
    
        const fetchData = async () => {
          const res = await fetch(url);
          setData(await res.json());
        };
    
        fetchData();
        const id = setInterval(fetchData, intervalMs);
        return () => clearInterval(id);
      }, [url, intervalMs, visibility]);
    
      return data;
    }
  5. Compare usePreferredDark with related theme hooks

    main

    Depending on your requirements for theme management, you might choose a different hook:

    • usePreferredDark: Returns a simple boolean (true for dark, false otherwise). Best for simple dark/light logic.
    • usePreferredColorScheme: Returns a string: "dark", "light", or "no-preference". Use this if you need to handle the case where no preference is detected.
    • useDarkMode: Provides a toggle mechanism that persists the user's choice in localStorage.
    • useColorMode: Designed for applications supporting multiple themes (beyond just light and dark).
  6. Use useIsomorphicLayoutEffect for layout-sensitive SSR components

    main

    Use useIsomorphicLayoutEffect only when all the following conditions are met:

    1. Layout-phase timing is required: You are measuring or mutating the DOM (e.g., getBoundingClientRect, scrollHeight) and the result must be visible in the very first painted frame to avoid a flicker (e.g., tooltips, popovers, autosizing textareas, scroll restoration).
    2. The component is server-rendered: You are using a framework like Next.js, Remix, Astro, or Gatsby.
    3. You want to keep SSR enabled: You want to avoid disabling SSR for the component subtree (which would happen if you used ssr: false or client-only guards).

    When NOT to use it:

    • If your effect does not touch layout (e.g., data fetching, event subscriptions, localStorage sync), use useEffect instead. useIsomorphicLayoutEffect runs synchronously and blocks paint, which can cause jank if overused.
  7. Choosing the right hook for cross-tab synchronization

    main
    ScenarioRecommended HookReason
    Persistent state needing cross-tab syncuseLocalStorageData survives refreshes; storage event provides sync
    Tab-scoped state (no sync needed)useSessionStorageEach tab is isolated; no cross-tab events
    Real-time imperative messagesuseBroadcastChannelFast, supports structured data, no persistence overhead
    Both persistence and instant messaginguseLocalStorage + useBroadcastChannelBest of both: persistence for new tabs, broadcasting for active tabs
    Pausing background workuseDocumentVisibility / useWindowFocusReduces unnecessary computation and network requests
  8. SSR Safety and Compatibility

    main

    ReactUse hooks are designed to be SSR-safe. Every hook checks for browser availability before accessing any API. During server-side rendering (SSR), hooks return safe default values and skip browser-only logic, preventing hydration mismatches in frameworks like Next.js, Remix, or Astro.

    Compatibility:

    • Supports React 16.8 and above.
    • Fully compatible with React 18 concurrent features and React 19.
  9. Use SSR-safe hooks from @reactuses/core

    main

    ReactUse hooks are designed to be SSR-compatible out of the box using several strategies:

    • isBrowser protection: Used to protect side-effect registration without branching initial render output.
    • useIsomorphicLayoutEffect: Replaces useLayoutEffect to avoid SSR warnings.
    • useSupported: A utility hook that safely checks if a browser API exists; it returns false on the server and performs the real check in an effect.
    • useSyncExternalStore with server snapshots: Hooks like useWindowSize use this to provide a stable fallback (e.g., { width: 0, height: 0 }) on the server.
    • Safe initial states: Hooks like useMediaQuery accept a defaultState parameter to allow you to control the server-rendered value and prevent mismatches.
  10. Important considerations for useActiveElement

    main

    When using useActiveElement, keep the following technical constraints in mind:

    • SSR Safety: The hook returns null during Server-Side Rendering (SSR) because document is not accessible on the server.
    • Shadow DOM: The hook tracks document.activeElement by default. If your application uses Shadow DOM, focus tracking may be limited to the shadow root.
    • Related Hooks:
      • Use useFocus for programmatic control of an element's focus.
      • Use useWindowFocus to track whether the browser window itself has focus.
  11. When to use useFetchEventSource vs useEventSource

    main

    Choosing between these two hooks depends on your endpoint's requirements:

    • Use useFetchEventSource when: You need to send a POST request, include custom Authorization headers, or provide a request body. This is the standard approach for modern AI/LLM streaming interfaces.
    • Use useEventSource when: You are connecting to a standard SSE endpoint that only requires a simple GET request without special headers or bodies.