ReactUse

website·Indexed 32 days ago

https://reactuse.com/

A collection of essential React hooks for managing browser APIs, element interactions, and side effects. The library includes specialized hooks such as useWindowSize, useClipboard, useColorMode, useGeolocation, and useAsyncEffect to simplify common development tasks.

Tokens
39.7K
Snippets
164
Records
208
Agent score
64%

What's inside ReactUse

  1. Prevent SSR warnings with useIsomorphicLayoutEffect

    useIsomorphicLayoutEffect is a drop-in replacement for useEffect and useLayoutEffect that resolves to useLayoutEffect in the browser and useEffect on the server. This prevents the common React warning about useLayoutEffect doing nothing during server-side rendering (SSR) while maintaining synchronous DOM measurement behavior on the client. It is ideal for projects using Next.js or Remix.
    import { useIsomorphicLayoutEffect } from '@reactuses/core';
    
    function Demo() {
      const [value] = useState("useIsomorphicLayoutEffect");
      useIsomorphicLayoutEffect(() => {
        window.console.log(value);
      }, [value]);
    
      return <div>{value}</div>;
    }
  2. Access media devices with useMediaDevices

    The useMediaDevices hook allows a developer to retrieve information about the available media devices (such as microphones and cameras) and their current state. By setting the requestPermissions option to true, the hook will automatically prompt the user for permission to access these devices upon initialization.
    function Demo() {
      const [state] = useMediaDevices({
        requestPermissions: true,
      });
    
      return <pre>{JSON.stringify(state, null, 2)}</pre>;
    };
  3. Monitor network connectivity with useNetwork

    The useNetwork hook tracks the current network connectivity status of the browser. It returns a state object containing information about the online/offline status and the type of connection.
    import { useNetwork } from 'react-use';
    
    function Demo() {
      const state = useNetwork();
    
      return <pre>{JSON.stringify(state, null, 2)}</pre>;
    };
  4. Track screen pixel density with useDevicePixelRatio

    useDevicePixelRatio is a React hook that reactively tracks window.devicePixelRatio, which represents the ratio of physical pixels to CSS pixels on the current display. It returns an object containing the pixelRatio property. The value updates automatically when the user changes their system zoom level or moves the browser window between monitors with different pixel densities.

    Common use cases include:

    • Rendering high-DPI (Retina) images or canvas elements at the correct resolution.
    • Adjusting visual fidelity based on display density.
    • Displaying device characteristics in developer tools.

    Key technical details:

    • SSR-safe: Returns a default pixelRatio of 1 during server-side rendering to avoid window access errors.
    • Reactivity: Uses matchMedia to listen for density changes in real-time.
    • Alternative: For general media query tracking, use the useMediaQuery hook.
    import { useDevicePixelRatio } from '@reactuses/core';
    
    const { pixelRatio } = useDevicePixelRatio();
  5. Detect long-press gestures with useLongPress

    The useLongPress hook detects long-press gestures on any element by tracking mousedown/mouseup and touchstart/touchend events. It returns an object of event handlers that should be spread onto the target element. When the user presses and holds for the configured delay (default: 300ms), the provided callback function is executed.

    Key features include:

    • Cross-platform support: Works with both mouse and touch interactions.
    • SSR-safe: Returns no-op event handlers during server-side rendering to avoid window or document access errors.
    • Default Behavior: By default, it prevents text selection and browser context menus during the press via the isPreventDefault option.
    import { useLongPress } from '@reactuses/core';
    
    const MyComponent = () => {
      const { 1longPressHandlers } = useLongPress(
        () => {
          console.log('Long press triggered!');
        },
        { delay: 500, isPreventDefault: true }
      );
    
      return <button {...longPressHandlers}>Press and Hold Me</button>;
    };
  6. Detect DOM elements at specific coordinates with useElementByPoint

    useElementByPoint is a React hook that reactively queries the DOM to find the element at given x and y coordinates. It wraps the native document.elementFromPoint() (or elementsFromPoint() in multi-mode).

    This hook is particularly useful for:

    • Element-inspection tools or visual debuggers.
    • Custom drag-and-drop logic to detect drop targets.
    • Interactive tutorials or onboarding overlays that identify UI elements under a cursor.

    The hook returns a pausable object containing the matched element, an isSupported flag, and pause/resume controls. It is SSR-safe, returning isSupported: false and a null element when rendered on the server.

    import { useElementByPoint } from '@reactuses/core'
    
    // Usage example: combine with useMouse to track element under cursor
    const { element, isSupported, pause, resume } = useElementByPoint(x, y);
  7. Manage a timed pending state with useTimeout

    useTimeout provides a reactive boolean state (isPending) that flips from true to false after a specified delay. It is useful for showing loading indicators for a minimum duration or implementing auto-dismiss behavior for notifications. By default, the timer starts on mount; use { immediate: false } to start it manually via the start() function.
    import { useTimeout } from '@reactuses/core';
    
    function Demo() {
      // [isPending, start, cancel] = useTimeout(delay, options)
      const [isPending, start, cancel] = useTimeout(5000);
    
      return (
        <div>
          <div>Pending: {JSON.stringify(isPending)}</div>
          <button onClick={() => start()}>Start Again</button>
          <button onClick={() => cancel()}>Cancel</button>
        </div>
      );
    }
  8. Detect user motion preference with useReducedMotion

    The useReducedMotion hook tracks whether a user has requested reduced motion via their system accessibility settings. It uses window.matchMedia() with the prefers-reduced-motion media query and returns a boolean. The value updates automatically if the user changes their system settings while the application is running.

    Use this hook to:

    • Disable or simplify complex CSS/JS animations for users with vestibular disorders.
    • Replace animated transitions with instant state changes.
    • Switch between animated and static UI elements (e.g., disabling parallax effects or auto-playing carousels).
    import { useReducedMotion } from '@reactuses/core';
    
    const MyComponent = () => {
      const prefersReducedMotion = useReducedMotion();
    
      return (
        <div className={prefersReducedMotion ? 'static-ui' : 'animated-ui'}>
          {/* Content */}
        </div>
      );
    };
  9. Subscribe to Server-Sent Events (SSE) using useFetchEventSource

    useFetchEventSource is a React hook that enables subscriptions to Server-Sent Events (SSE) using the Fetch API instead of the native EventSource constructor. This allows developers to use HTTP methods other than GET (such as POST or PUT), include custom request headers, and send request bodies—capabilities not available in the standard EventSource API.

    This hook is particularly useful for:

    • Streaming responses from AI/LLM APIs that require POST requests with JSON payloads.
    • Connecting to SSE endpoints requiring authentication headers or custom content types.
    • Building real-time chat or code generation interfaces.

    Key characteristics:

    • SSR-safe: No fetch calls occur during server-side rendering; it returns a default state until mounted in the browser.
    • Flexibility: Supports any HTTP method, headers, and body, making it compatible with endpoints like the OpenAI streaming API.
    import { useFetchEventSource } from '@reactuses/core'
  10. Evaluate CSS media queries reactively with useMediaQuery

    The useMediaQuery hook wraps the native window.matchMedia() API to reactively evaluate a CSS media query string. It returns a boolean indicating whether the document currently matches the query and automatically updates the value when the match state changes (e.g., window resizing or system setting changes).

    Common use cases include:

    • Rendering different layouts based on screen width breakpoints.
    • Detecting system preferences such as dark mode, reduced motion, or high contrast.
    • Conditionally loading assets or components based on screen size.

    It is SSR-safe; it accepts an optional defaultState parameter (which defaults to false) to be returned during server-side rendering when window.matchMedia is unavailable.

    import { useMediaQuery } from '@reactuses/core';
    
    // Example: Detect if the screen is wider than 768px
    const isDesktop = useMediaQuery('(min-width: 768px)');
    
    // Example: Detect dark mode preference with a custom SSR default
    const prefersDark = useMediaQuery('(prefers-color-scheme: dark)', true);
  11. Lock element scrolling with useScrollLock

    The useScrollLock hook prevents scrolling on a target element by applying overflow: hidden to its style. It is specifically designed for modals, dialogs, and overlays because it preserves the ability to scroll within nested scrollable containers inside the locked element. The lock is automatically released when the component using the hook unmounts. The hook is SSR-safe, returning false for the lock state and a no-op setter during server-side rendering.
    import { useScrollLock } from '@reactuses/core';
    
    const [isLocked, setLock] = useScrollLock();
    
    // Use setLock(true) to lock scrolling
    // Use setLock(false) to unlock scrolling
  12. Smoothly scroll to an element using useScrollIntoView

    The useScrollIntoView hook provides a smooth, animated scroll to a target element ref. It functions similarly to the native Element.scrollIntoView() API but adds control over the scroll axis, duration, easing functions, and offsets. It is SSR-safe and returns no-op functions during server-side rendering.

    Key features include:

    • Alignment: Supports alignment options such as "start", "end", and "center".
    • Interruptibility: By default, users can interrupt the animation by manually scrolling (cancelable: true).
    • List Optimization: Setting isList: true helps prevent content jumping when scrolling within lists.
    • Cancellation: Provides a cancel function to programmatically stop the animation.
    import { useScrollIntoView } from '@reactuses/core';
    
    // Usage example
    const { scrollIntoView, cancel } = useScrollIntoView(elementRef, {
      duration: 500, // duration in ms
      easing: 'ease-in-out', // easing function
      cancelable: true, // allow user to interrupt
      isList: false // prevent jumping in lists
    });
    
    // Trigger scroll to the center of the element
    scrollIntoView('center');