usehooks-ts

repository·master·Indexed 9 days ago

https://github.com/juliencrn/usehooks-ts

A minimal, tree-shakable React hooks library written in TypeScript. It provides a collection of extensively tested hooks for common use cases, including state management (useBoolean, useCounter), browser APIs (useLocalStorage, useWindowSize), events and observers (useEventListener, useIntersectionObserver), timers (useCountdown, useInterval), and utilities (useDebounceCallback, useCopyToClipboard).

Tokens
6.1K
Snippets
7
Records
52
Agent score
79%

What's inside usehooks-ts

  1. Use the useScreen hook to retrieve window.screen data

    master

    The useScreen hook allows you to easily retrieve the window.screen object in React. It automatically updates when the window is resized.

    Parameters

    • initializeWithValue: (Optional, boolean) If you are using this hook in a Server-Side Rendering (SSR) context, set this to false. This ensures the hook initializes with undefined instead of attempting to access window immediately. Defaults to true.
    • debounceDelay: (Optional, number) The delay in milliseconds before the resize callback is invoked. This is useful for performance optimization during window resizing. Defaults to 0 (disabled).
  2. Polyfill ResizeObserver for useResizeObserver

    master

    The useResizeObserver hook does not include a built-in polyfill. If you need to support environments where window.ResizeObserver is not available, it is recommended to provide a polyfill (e.g., @juggle/resize-observer) by re-exporting the hook after attaching the polyfill to the window object.

    // useResizeObserver.ts
    import { ResizeObserver } from '@juggle/resize-observer'
    import { useResizeObserver } from 'usehooks-ts'
    
    if (!window.ResizeObserver) {
      window.ResizeObserver = ResizeObserver
    }
    
    export { useResizeObserver }
  3. Use the useLocalStorage hook to persist state

    master

    The useLocalStorage hook allows you to persist state in the browser's localStorage so that it remains after a page refresh (e.g., for theme preferences).

    It functions similarly to useState, but requires a storage key as the first argument.

    Usage for SSR: If using this hook in a Server-Side Rendering (SSR) context, set the initializeWithValue option to false. This ensures the hook initializes with the provided initial value during SSR to avoid hydration mismatches.

    Custom Serialization: You can provide an optional third parameter to pass a custom serializer/deserializer if you need to handle complex data types beyond standard JSON.

  4. Use useLocalStorage hook

    master

    The useLocalStorage hook allows you to persist state across page reloads using the localStorage API. It takes a key and an initial value as arguments.

    import { useLocalStorage } from 'usehooks-ts'
    
    function Component() {
      const [value, setValue] = useLocalStorage('my-localStorage-key', 0)
    
      // ...
    }
  5. Use the useDebounceValue hook

    master

    The useDebounceValue hook returns a debounced version of a provided value and a function to update that value. It is useful for delaying state updates (like search input) to prevent excessive re-renders or API calls. This hook is built upon lodash.debounce and provides fine-grained control over the debouncing behavior.

    Parameters

    • value: The value to be debounced.
    • delay: The delay in milliseconds before the value is updated.
    • options (optional): Configuration for debouncing behavior:
      • leading (optional): If true, the debounced function is invoked on the leading edge of the timeout.
      • trailing (optional): If true, the debounced function is invoked on the trailing edge of the timeout.
      • maxWait (optional): The maximum time the debounced function is allowed to be delayed before it's invoked.
      • equalityFn (optional): A custom equality function to compare the current and previous values.

    Returns

    An array containing:

    1. The debounced value.
    2. A function to update the value.
  6. Use the useWindowSize hook

    master

    The useWindowSize hook allows you to easily retrieve the current window dimensions (width and height) and automatically updates them on the window onResize event.

    Parameters

    ParameterTypeDefaultDescription
    initializeWithValuebooleantrueIf using this hook in a Server-Side Rendering (SSR) context, set this to false to avoid hydration mismatches.
    debounceDelaynumberundefinedThe delay in milliseconds before the resize callback is invoked. Note: This is disabled by default for retro-compatibility.
  7. Use the useEventCallback hook

    master

    The useEventCallback hook is a utility for creating memoized event callback functions in React applications. It ensures that the provided callback function is memoized and stable across renders, while also preventing its invocation during the render phase. This is particularly useful for handling callbacks that need to access frequently changing values without causing the callback identity to change on every render.

    Parameters:

    • fn: (args) => result: The callback function to be memoized.

    Return Value:

    • (args) => result: A memoized event callback function that maintains a stable identity.

    Key Features:

    • Memoization: Optimizes performance by providing a stable function identity.
    • Render Safety: Prevents the callback from being invoked during the render phase. It will throw an error if you attempt to call it during rendering.
    • Strict Mode Compatibility: Designed to work seamlessly with React's strict mode.

    Note: Avoid using useEventCallback for callback functions that depend on frequently changing state or props if you expect the callback's behavior to change based on those values in a way that requires a new function identity.

  8. Understand the useIntersectionObserver return value

    master

    The hook returns an IntersectionResult object which can be destructured. It contains:

    • ref: A function used as a ref callback to set the target element to be observed.
    • isIntersecting: A boolean indicating if the target element is currently intersecting with the viewport.
    • entry: An optional IntersectionObserverEntry object representing the detailed state of the intersection.
  9. Use the useDebounceCallback hook

    master

    The useDebounceCallback hook creates a debounced version of a callback function. This is useful for preventing a function from being called too frequently (e.g., during rapid user input or window resizing).

    Parameters

    • func: The callback function to be debounced.
    • delay (optional): The delay in milliseconds before the callback is invoked (default is 500 milliseconds).
    • options (optional): Options to control the behavior of the debounced function.

    Returns

    A debounced version of the original callback along with control functions.

    Dependency

    This hook is built upon lodash.debounce.