react-use

repository·master·Indexed 13 days ago

https://github.com/streamich/react-use

A comprehensive collection of essential React Hooks version 17.6.1 designed to simplify common tasks. It provides categorized hooks for sensors (device state, user input), UI interactions, animations, side-effects (browser storage, clipboard), lifecycles, and advanced state management patterns including global state and memoized hooks.

Tokens
54.9K
Snippets
213
Records
236
Agent score
96%

What's inside react-use

  1. Overview of react-use hooks

    master

    react-use is a collection of essential React Hooks categorized into several functional groups to help manage various aspects of web applications. The library is a port of libreact and provides hooks for:

    • Sensors: Tracking device state (battery, geolocation, orientation), user input (mouse, keyboard, touch, idle), and browser/window properties (scroll, size, media queries, network state).
    • UI: Managing UI interactions and elements (audio, video, fullscreen, click-away, drag-and-drop, sliders, speech, vibration).
    • Animations: Handling time-based and frame-based updates (requestAnimationFrame, intervals, timeouts, spring dynamics, tweens).
    • Side-effects: Managing asynchronous operations, browser storage (cookies, localStorage, sessionStorage), clipboard, debouncing, throttling, and page metadata (title, favicon).
    • Lifecycles: Enhancing standard React lifecycle hooks (mounting/unmounting, effect timing, deep comparison, isomorphic layout effects).
    • State: Advanced state management patterns (reducers, memoized hooks, global state, specialized collections like Maps, Sets, Lists, and Queues, and state history).
  2. Manage state for booleans, arrays, and maps with State Hooks

    master
    The react-use library provides specialized hooks (referred to as "State Hooks") designed to simplify the management of common state types in React, specifically booleans, arrays, and maps. These hooks abstract away the boilerplate of manual state updates (like spreading arrays or setting new map instances) to ensure state updates are handled correctly and idiomatically.
  3. What are UI Hooks?

    master
    In react-use, UI Hooks are specialized hooks designed to allow you to control and subscribe to the state changes of various UI elements (such as visibility, focus, or scroll positions). They bridge the gap between raw DOM events and React state management.
  4. Implement asynchronous validation with `useStateValidator`

    master

    To prevent useStateValidator from triggering automatic state updates on every render (which is necessary for async operations), use the setValidity callback provided as the second argument to your validator function. This allows you to control exactly when the validity state is updated, typically after an asynchronous task completes.

    // Conceptual pattern for async validation
    const asyncValidator = async (state, setValidity) => {
      // 1. Perform async check
      const result = await checkServer(state);
      
      // 2. Manually update validity once finished
      // This prevents the hook from updating 'isValid' prematurely
      setValidity([result, 'metadata']);
      
      // Return the current state to satisfy the signature
      return [null, 'pending'];
    };
  5. Use `useHarmonicIntervalFn` for synchronized interval effects

    master

    The useHarmonicIntervalFn hook functions similarly to the useInterval hook, but with a key difference: it triggers all registered effects with the same delay at the exact same time. This is specifically useful for creating synchronized UI elements, such as multiple ticking clocks on a page that need to re-render their counters simultaneously to prevent visual drift.

    // Example use case: synchronized clocks
    useHarmonicIntervalFn(() => {
      // This effect will trigger in sync with other harmonic intervals
      setSeconds(s => s + 1);
    }, 1000);
  6. Compare `useDrop` and `useDropArea`

    master

    Choose between the two hooks based on the scope of your drop detection:

    • useDrop: Tracks events for the whole page. Use this for global interactions where dropping anywhere on the document should trigger an action.
    • useDropArea: Tracks drop events for a specific element. Use this when you want to define a specific 'drop zone' (e.g., a file upload box) by spreading the returned bond object onto that element.
  7. Difference between reset() and clear() in useSet

    master

    When using the useSet hook, you can choose between two ways to empty or revert the state:

    1. reset(): Returns the Set to the initial value that was passed to useSet during the initial render.
    2. clear(): Completely empties the Set, leaving it with no elements regardless of the initial value.
  8. How `createReducerContext` works

    master

    createReducerContext is a factory for React context hooks that mimics the behavior of React's useReducer hook, but with a key difference: the state is shared among all components wrapped within the returned Provider. This pattern is useful for managing global or shared state that any component in a specific subtree can read and update via a dispatch function.

    import { createReducerContext } from 'react-use';
    
    const reducer = (state, action) => {
      // ... reducer logic
    };
    
    const [useSharedState, SharedStateProvider] = createReducerContext(reducer, initialState);
  9. What are Sensor Hooks?

    master
    Sensor Hooks are specialized React hooks designed to listen to changes in external interfaces (such as window resizing, scroll position, or mouse movements). When these interfaces change, the sensor hook triggers a re-render of your component, ensuring the component state remains synchronized with the up-to-date interface state.
  10. What are Lifecycle Hooks in react-use

    master
    Lifecycle Hooks in react-use are specialized hooks designed to either modify and extend built-in React hooks or to imitate the lifecycle patterns found in React Class components (such as componentDidMount, componentDidUpdate, etc.) within a functional component environment.
  11. Why use `useGetSet` instead of `useState`?

    master

    When using standard useState, if you trigger an asynchronous operation (like setTimeout) that references the state variable, that variable is captured from the render cycle in which the function was created. If the state changes before the async operation completes, the operation will use the old (stale) value.

    useGetSet solves this by providing a get() function that always retrieves the current state value from the latest render, ensuring asynchronous updates are based on the most recent data.

    // WRONG: Using useState with async operations captures stale 'cnt'
    const DemoWrong = () => {
      const [cnt, set] = useState(0);
      const onClick = () => {
        setTimeout(() => {
          set(cnt + 1);
        }, 1_000);
      };
    
      return (
        <button onClick={onClick}>Clicked: {cnt}</button>
      );
    };
  12. Use the `useSessionStorage` hook

    master

    The useSessionStorage hook is a React side-effect hook that manages a single key within the browser's sessionStorage. It provides a state-like interface ([value, setValue]) where updates are automatically persisted to sessionStorage.

    import {useSessionStorage} from 'react-use';
    
    const Demo = () => {
      // Manages 'my-key' with an initial value of 'foo'
      const [value, setValue] = useSessionStorage('my-key', 'foo');
    
      return (
        <div>
          <div>Value: {value}</div>
          <button onClick={() => setValue('bar')}>bar</button>
          <button onClick={() => setValue('baz')}>baz</button>
        </div>
      );
    };