use-debounce

repository·master·Indexed 25 days ago

https://github.com/xnimorz/use-debounce

A collection of React hooks for debouncing and throttling values and callback functions. Version 10.1.1 provides hooks including useDebounce for values, useDebouncedCallback for function execution, and useThrottledCallback for limiting execution frequency. Features include advanced options like maxWait, leading, and trailing edges, as well as lifecycle control methods such as cancel(), flush(), and isPending().

Tokens
2.6K
Snippets
7
Records
13
Agent score
84%

What's inside use-debounce

  1. Configure useDebounce options

    master

    The following options can be passed to useDebounce and useDebouncedCallback via an options object.

    | option | default | Description |
    | ---------- | - | :--- |
    | maxWait | - | Describes the maximum time func is allowed to be delayed before it's invoked |
    | leading | - | This param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires. |
    | trailing | true | This param executes the function after timeout. |
    | equalityFn | (prev, next) => prev === next | [useDebounce ONLY] Comparator function which shows if timeout should be started |
  2. Manage debounce lifecycle with cancel, flush, and isPending

    master

    Both hooks provide methods to control the debounce cycle:

    • cancel(): Cancels the pending debounce request.
    • flush(): Immediately executes the pending request.
    • isPending(): Returns a boolean indicating if there is a pending debounce request.

    useDebounce returns these as part of an array: [value, { cancel, isPending, flush }]. useDebouncedCallback returns these as properties on the returned function: debounced.cancel(), debounced.flush(), etc.

  3. Use useThrottledCallback

    master

    The useThrottledCallback hook allows you to limit the execution frequency of a callback function. It ensures the function is called at most once per specified interval.

    Available since version 5.2.0. You can import it either directly from the sub-module or from the main package.

    All parameters are identical to useDebouncedCallback, except that the maxWait option is not used for throttled callbacks.

  4. Use advanced options: maxWait, leading, and trailing

    master

    Both useDebounce and useDebouncedCallback accept an options object as a third argument to control execution behavior.

    • maxWait: The maximum time the function is allowed to be delayed before it is invoked.
    • leading: If true, the function executes immediately on the first call, then subsequent calls are debounced.
    • trailing: (Default: true) Controls whether the function is called again after the timeout expires.
    // Example with maxWait and cancel
    const debounced = useDebouncedCallback(
      (value) => {
        setValue(value);
      },
      500,
      { maxWait: 2000 }
    );
    
    // Example with leading
    const [value] = useDebounce(text, 1000, { leading: true });
  5. Control debounced functions with cancel, flush, and isPending

    master

    The function returned by useDebouncedCallback is an extended function that provides several control methods to manage pending executions:

    • cancel(): Cancels any pending function invocations and clears timers.
    • flush(): Immediately invokes any pending function invocations and returns the result of that invocation (or undefined if nothing was pending).
    • isPending(): Returns true if there are currently any pending function invocations scheduled.
  6. Use the useDebouncedCallback hook

    master

    The useDebouncedCallback hook creates a debounced version of a function that delays its execution until after a specified wait period has elapsed since the last time it was invoked.

    Key Behaviors:

    • Wait Time: If wait is omitted, it defaults to using requestAnimationFrame (approx. 16ms) if available in the environment. If wait is explicitly 0, it behaves like setTimeout(..., 0).
    • Return Value: Subsequent calls to the debounced function return the result of the last successful invocation. If no previous invocation has occurred, it returns undefined.
    • Control Methods: The returned function includes cancel(), flush(), and isPending() methods.
    • Leading/Trailing Edges: You can configure whether the function triggers at the start (leading) or end (trailing) of the timeout period.
    // 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</button>
    
    // 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.isPending() ? "Pending..." : "Ready";
  7. Configure useDebouncedCallback options

    master

    The useDebouncedCallback hook accepts an options object to fine-tune debouncing behavior.

    OptionTypeDefaultDescription
    leadingbooleanfalseIf true, the function is invoked on the leading edge of the timeout.
    trailingbooleantrueIf true, the function is invoked on the trailing edge of the timeout.
    flushOnExitbooleanfalseIf true, the function is invoked when the component unmounts or the page visibility changes to hidden. Note: This has no effect if trailing is false.
    maxWaitnumberundefinedThe maximum time the function is allowed to be delayed before it's forced to invoke.
    debounceOnServerbooleanfalseIf true, debouncing and timers will occur on the server side as well.
  8. Reference types for useDebouncedCallback

    master

    The following types are exported for use with the useDebouncedCallback hook to provide type safety for options and control functions:

    • CallOptions: Configuration options for invoking the debounced function.
    • ControlFunctions: Functions used to manually control the debounced callback (e.g., canceling or flushing).
    • DebouncedState: Represents the state of the debounced callback.
    • Options: Configuration options for initializing the hook.
    import type {
      CallOptions,
      ControlFunctions,
      DebouncedState,
      Options,
    } from 'use-debounce';
  9. Debounce a callback with useDebouncedCallback

    master

    Use the useDebouncedCallback hook to debounce a function execution. When using with React synthetic events (like onChange), pass the value directly to the debounced function rather than the event object itself.

    import { useDebouncedCallback } from 'use-debounce';
    
    function Input({ defaultValue }) {
      const [value, setValue] = useState(defaultValue);
      // Debounce callback
      const debounced = useDebouncedCallback(
        // function
        (value) => {
          setValue(value);
        },
        // delay in ms
        1000
      );
    
      // you should use `e => debounced(e.target.value)` as react works with synthetic events
      return (
        <div>
          <input
            defaultValue={defaultValue}
            onChange={(e) => debounced(e.target.value)}
          />
          <p>Debounced value: {value}</p>
        </div>
      );
    }
  10. Debounce a value with useDebounce

    master

    Use the useDebounce hook to debounce a specific value. The hook compares the previous and next value using shallow equality. If you need to compare objects using a custom comparator, use useDebouncedCallback instead.

    import React, { useState } from 'react';
    import { useDebounce } from 'use-debounce';
    
    export default function Input() {
      const [text, setText] = useState('Hello');
      const [value] = useDebounce(text, 1000);
    
      return (
        <div>
          <input
            defaultValue={'Hello'}
            onChange={(e) => {
              setText(e.target.value);
            }}
          />
          <p>Actual value: {text}</p>
          <p>Debounce value: {value}</p>
        </div>
      );
    }