use-debounce

  • Version 10.0.1
  • Published
  • 105 kB
  • No dependencies
  • MIT license

Install

npm i use-debounce
yarn add use-debounce
pnpm add use-debounce

Overview

Debounce hook for react

Index

Functions

function useDebounce

useDebounce: <T>(
value: T,
delay: number,
options?: {
maxWait?: number;
leading?: boolean;
trailing?: boolean;
equalityFn?: (left: T, right: T) => boolean;
}
) => [T, DebouncedState<(value: T) => void>];

    function useDebouncedCallback

    useDebouncedCallback: <T extends (...args: any) => ReturnType<T>>(
    func: T,
    wait?: number,
    options?: Options
    ) => DebouncedState<T>;
    • Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked, or until the next browser frame is drawn.

      The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them.

      Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function.

      Subsequent calls to the debounced function return the result of the last func invocation.

      **Note:** If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait timeout.

      If wait is 0 and leading is false, func invocation is deferred until the next tick, similar to setTimeout with a timeout of 0.

      If wait is omitted in an environment with requestAnimationFrame, func invocation will be deferred until the next frame is drawn (typically about 16ms).

      See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) for details over the differences between debounce and throttle.

      Function

      Parameter func

      The function to debounce.

      Parameter wait

      The number of milliseconds to delay; if omitted, requestAnimationFrame is used (if available, otherwise it will be setTimeout(...,0)).

      Parameter options

      The options object. Controls if func should be invoked on the leading edge of the timeout.

      Parameter

      {boolean} [options.leading=false] The maximum time func is allowed to be delayed before it's invoked.

      Parameter

      {number} [options.maxWait] Controls if func should be invoked the trailing edge of the timeout.

      Parameter

      {boolean} [options.trailing=true]

      Returns

      {Function} Returns the new debounced function.

      Example 1

      // Avoid costly calculations while the window size is in flux. const resizeHandler = useDebouncedCallback(calculateLayout, 150); window.addEventListener('resize', resizeHandler)

      // Invoke sendMail when clicked, debouncing subsequent calls. const clickHandler = useDebouncedCallback(sendMail, 300, { leading: true, trailing: false, }) <button onClick={clickHandler}>click me

      // Ensure batchLog is invoked once after 1 second of debounced calls. const debounced = useDebouncedCallback(batchLog, 250, { 'maxWait': 1000 }) const source = new EventSource('/stream') source.addEventListener('message', debounced)

      // Cancel the trailing debounced invocation. window.addEventListener('popstate', debounced.cancel)

      // Check for pending invocations. const status = debounced.pending() ? "Pending..." : "Ready"

    function useThrottledCallback

    useThrottledCallback: <T extends (...args: any) => ReturnType<T>>(
    func: T,
    wait: number,
    { leading, trailing }?: CallOptions
    ) => DebouncedState<T>;
    • Creates a throttled function that only invokes func at most once per every wait milliseconds (or once per browser frame).

      The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them.

      Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function.

      Subsequent calls to the throttled function return the result of the last func invocation.

      **Note:** If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.

      If wait is 0 and leading is false, func invocation is deferred until the next tick, similar to setTimeout with a timeout of 0.

      If wait is omitted in an environment with requestAnimationFrame, func invocation will be deferred until the next frame is drawn (typically about 16ms).

      See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) for details over the differences between throttle and debounce.

      Function

      Parameter func

      The function to throttle.

      Parameter wait

      The number of milliseconds to throttle invocations to; if omitted, requestAnimationFrame is used (if available, otherwise it will be setTimeout(...,0)).

      Parameter options

      The options object.

      Parameter

      {boolean} [options.leading=true] Specify invoking on the leading edge of the timeout.

      Parameter

      {boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.

      Returns

      {Function} Returns the new throttled function.

      Example 1

      // Avoid excessively updating the position while scrolling. const scrollHandler = useThrottledCallback(updatePosition, 100) window.addEventListener('scroll', scrollHandler)

      // Invoke renewToken when the click event is fired, but not more than once every 5 minutes. const throttled = useThrottledCallback(renewToken, 300000, { 'trailing': false }) <button onClick={throttled}>click

      // Cancel the trailing throttled invocation. window.addEventListener('popstate', throttled.cancel);

    Interfaces

    interface CallOptions

    interface CallOptions {}

      property leading

      leading?: boolean;
      • Controls if the function should be invoked on the leading edge of the timeout.

      property trailing

      trailing?: boolean;
      • Controls if the function should be invoked on the trailing edge of the timeout.

      interface ControlFunctions

      interface ControlFunctions<ReturnT> {}

        property cancel

        cancel: () => void;
        • Cancel pending function invocations

        property flush

        flush: () => ReturnT | undefined;
        • Immediately invoke pending function invocations

        property isPending

        isPending: () => boolean;
        • Returns true if there are any pending function invocations

        interface DebouncedState

        interface DebouncedState<T extends (...args: any) => ReturnType<T>>
        extends ControlFunctions<ReturnType<T>> {}
        • Subsequent calls to the debounced function return the result of the last func invocation. Note, that if there are no previous invocations you will get undefined. You should check it in your code properly.

        call signature

        (...args: Parameters<T>): ReturnType<T> | undefined;

          interface Options

          interface Options extends CallOptions {}

            property debounceOnServer

            debounceOnServer?: boolean;
            • If the setting is set to true, all debouncing and timers will happen on the server side as well

            property maxWait

            maxWait?: number;
            • The maximum time the given function is allowed to be delayed before it's invoked.

            Package Files (4)

            Dependencies (0)

            No dependencies.

            Dev Dependencies (28)

            Peer Dependencies (1)

            Badge

            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/use-debounce.

            • Markdown
              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/use-debounce)
            • HTML
              <a href="https://www.jsdocs.io/package/use-debounce"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>