@react-hookz/web Documentation

repository·master·Indexed 24 days ago

https://github.com/react-hookz/web

A library of general-purpose React hooks designed for browser and SSR compatibility. It provides a wide range of utilities categorized by functionality, including callback control (debouncing, throttling), lifecycle management (mount/update effects), advanced state management (List, Map, Toggle), browser-level navigator and sensor tracking, DOM interactions, and side-effect management for async operations and storage.

Tokens
15.8K
Snippets
11
Records
103
Agent score
79%

What's inside @react-hookz/web

  1. Overview of @react-hookz/web hooks

    master

    The library provides a wide range of general-purpose React hooks categorized by functionality:

    • Callback: Debounced, throttled, or RAF-based callbacks (e.g., useDebouncedCallback, useRafCallback).
    • Lifecycle: Specialized effect hooks (e.g., useMountEffect, useUpdateEffect, useIsomorphicLayoutEffect, useDeepCompareEffect).
    • State: Advanced state management (e.g., useToggle, useList, useMap, useDebouncedState, usePrevious).
    • Navigator: Browser-level state tracking (e.g., useNetworkState, usePermission).
    • Side-effect: Async operations and storage management (e.g., useAsync, useCookieValue, useLocalStorageValue).
    • Sensor: Browser APIs for observation (e.g., useIntersectionObserver, useMediaQuery, useWindowSize).
    • Dom: DOM interaction (e.g., useClickOutside, useEventListener).
    • Miscellaneous: Ref and memoization utilities (e.g., useSyncedRef, useDeepCompareMemo).
  2. Install @react-hookz/web

    master

    Install the library using npm or yarn. Note that @react-hookz/web requires react and react-dom version 16.8 or higher. It does not support Internet Explorer.

    npm i @react-hookz/web
    # or
    yarn add @react-hookz/web
  3. Import hooks from @react-hookz/web

    master

    The package is distributed using ESNext and ES modules. Depending on your browser target, you may need to transpile it via your bundler. You can import hooks in two ways:

    1. From the root: Best for modern bundlers with tree-shaking support.
    2. Directly from the hook path: Recommended if your bundler does not support tree-shaking to ensure only the necessary code is included in your bundle.
    // from the root of package
    import {useMountEffect} from '@react-hookz/web';
    
    // or single hook directly
    import {useMountEffect} from '@react-hookz/web/useMountEffect';
  4. Configure useStorageValue options

    master

    The useStorageValue hook accepts a UseStorageValueOptions object to customize how data is handled.

    Default Behavior

    By default, the hook uses JSON.parse for parse and JSON.stringify for stringify. It also attempts to initialize the state with the storage value immediately on the first render.

    Custom Parsing and Stringifying

    If you are storing non-JSON data (like a plain string or a custom format), provide your own functions:

    useStorageValue(window.localStorage, 'user-name', {
      defaultValue: 'Guest',
      parse: (str) => (str === null ? 'Guest' : str),
      stringify: (val) => val,
    });

    Deferred Initialization

    To avoid potential hydration mismatches in SSR (Server-Side Rendering) environments, set initializeWithValue: false. This ensures the hook returns undefined on the initial render, deferring the storage read until the component mounts in the browser.

    const { value } = useStorageValue(window.localStorage, 'key', {
      initializeWithValue: false,
    });
  5. Use the useThrottledCallback hook

    master

    The useThrottledCallback hook returns a throttled version of a callback function. It ensures that the provided function is executed at most once every delay milliseconds. This is useful for limiting the execution rate of high-frequency events like scrolling, resizing, or mouse movements.

    Parameters

    • callback: The function to be throttled.
    • deps: A dependency list (similar to useCallback) that determines when the throttled function should be updated.
    • delay: The throttle delay in milliseconds.
    • noTrailing (optional): A boolean that defaults to false.
      • If false (default), the callback will execute one final time after the last throttled call using the most recent arguments (trailing edge execution).
      • If true, the callback will only execute at the start of the delay period and will not execute a final time after the last call if it falls within the delay window.
  6. useConditionalEffect API Reference

    master

    The useConditionalEffect function accepts the following arguments:

    ArgumentTypeDescription
    callbackCallbackThe function to be passed to the underlying effect hook.
    depsDepsA dependency list (similar to useEffect). If undefined, the effect triggers on every render.
    conditionsCondA list of conditions to be evaluated by the predicate.
    predicateConditionsPredicate<Cond>A function that determines if the conditions satisfy the requirement. Defaults to truthyAndArrayPredicate (checks if all conditions are truthy).
    effectHookEffectHook<...>The effect hook to use (e.g., useEffect). Defaults to useEffect. Must accept callback as the first argument and deps as the second.
    ...effectHookRestArgsRAdditional arguments passed to the effectHook after the callback and dependency list.
  7. ListActions API reference

    master

    The ListActions<T> object provides the following methods for manipulating the list:

    MethodDescription
    set(newList: SetStateAction<T[]>)Replaces the current list with a new one.
    push(...items: T[])Adds one or more items to the end of the list.
    updateAt(index: number, newItem: T)Replaces the item at the specified index. If the index is out of bounds, empty elements are appended until the index is reached.
    insertAt(index: number, item: T)Inserts an item at the specified index, shifting subsequent items. If the index is out of bounds, empty elements are appended until the index is reached.
    update(predicate: (iteratedItem: T, newItem: T) => boolean, newItem: T)Replaces all items that match the predicate with newItem.
    updateFirst(predicate: (iteratedItem: T, newItem: T) => boolean, newItem: T)Replaces only the first item that matches the predicate with newItem.
    upsert(predicate: (iteratedItem: T, newItem: T) => boolean, newItem: T)Replaces the first item matching the predicate with newItem. If no match is found, newItem is pushed to the end.
    sort(compareFn?: (a: T, b: T) => number)Sorts the list using the provided compareFn (defaults to Array.prototype.sort()).
    filter(callbackFn: (value: T, index?: number, array?: T[]) => boolean, thisArg?: any)Filters the list based on the callbackFn.
    removeAt(index: number)Removes the item at the specified index and shifts subsequent items. If the index is out of bounds, the list is not modified but a rerender occurs.
    clear()Removes all items from the list.
    reset()Reverts the list to its initial state provided to the hook.
  8. Use the useStorageValue hook

    master

    The useStorageValue hook manages a piece of state that is automatically synchronized with web storage (such as localStorage or sessionStorage). It handles reading, writing, and listening to changes made to the storage key, even from other browser tabs.

    Usage

    Pass the storage object (e.g., window.localStorage), a unique key, and an optional options object to the hook. It returns an object containing the current value and several action methods: set, remove, and fetch.

    Options

    • defaultValue: The value to return if the key is not present in storage. Defaults to undefined.
    • initializeWithValue: If true (default), the hook fetches the value from storage during the first render. If false, the hook yields undefined on the first render and fetches the value during the effect phase.
    • parse: A custom function to parse the string retrieved from storage. Receives the raw string and the defaultValue as arguments.
    • stringify: A custom function to convert the value into a string for storage. Defaults to JSON.stringify behavior.

    API Result

    The hook returns a UseStorageValueResult object:

    • value: The current state of the stored item.
    • set(value): Updates the state and persists the new value to storage.
    • remove(): Deletes the item from storage.
    • fetch(): Manually triggers a re-fetch of the value from storage.
  9. Use the useCookieValue hook

    master

    The useCookieValue hook manages the state and lifecycle of a single cookie. It provides methods to set, remove, and manually re-fetch the cookie value. It also synchronizes state across multiple components using the same cookie key: when one instance updates the cookie, all other active useCookieValue hooks watching that same key will update their local state.

    SSR Considerations

    If you are using Server-Side Rendering (SSR), it is highly recommended to set initializeWithValue: false in the options. This prevents hydration mismatches by ensuring the initial state is undefined on the server and only fetches the actual cookie value once mounted in the browser.

    Dependencies

    This hook requires the js-cookie package to be installed in your project.

  10. useCounter configuration parameters

    master

    The useCounter hook accepts the following arguments:

    • initialValue: The starting numeric value. Defaults to 0. Can be a value or a function returning a value.
    • max (optional): The maximum value the counter is allowed to reach. If initialValue > max, the counter starts at max.
    • min (optional): The minimum value the counter is allowed to reach. If initialValue < min, the counter starts at min.
  11. Use Sensor hooks

    master

    Hooks for observing browser sensors, layout changes, and environmental properties.

    Available hooks:

    • useIntersectionObserver
    • useResizeObserver
    • useMeasure
    • useMediaQuery
    • useKeyboardEvent
    • useDocumentVisibility
    • useScreenOrientation