npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@custom-react-hooks/use-debounce

v1.5.1

Published

The `useDebounce` hook is used to delay the execution of a function until a specified amount of time has passed since it was last invoked. This is useful for handling rapid user input scenarios, such as search input fields or window resizing.

Downloads

967

Readme

useDebounce Hook

The useDebounce hook is used to delay the execution of a function until a specified amount of time has passed since it was last invoked. This is useful for handling rapid user input scenarios, such as search input fields or window resizing.

Installation

Choose and install individual hooks that suit your project needs, or install the entire collection for a full suite of utilities.

Installing Only Current Hooks

npm install @custom-react-hooks/use-debounce

or

yarn add @custom-react-hooks/use-debounce

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Importing the Hook

The useDebounce hook must be imported using a named import as shown below:

Named Import:

import { useDebounce } from '@custom-react-hooks/use-debounce';

This approach ensures that the hook integrates seamlessly into your project, maintaining consistency and predictability in how you use our package.

Features

  • Function Execution Delay: Delays the execution of a function until a certain amount of time has passed since its last invocation, effectively controlling the rate at which the function fires.

  • Configurable Delay and Max Wait: Offers the flexibility to set both a delay for the debounce and a maximum waiting time, ensuring the function is executed after a certain period even if the input continues.

  • Leading and Trailing Edge Execution: Provides options for executing the function at the start (leading edge) or at the end (trailing edge) of the debounce delay, catering to different use case requirements.

  • Improved Performance in Rapid Input Scenarios: Particularly useful in scenarios involving rapid user inputs, such as typing in search fields or adjusting UI elements, to prevent excessive function calls.

  • Cancel Functionality: Includes a mechanism to cancel the debounced action, offering additional control over the debounced function's behavior.

  • Optimized for User Interaction Scenarios: Ideal for use cases like search inputs, form validations, or any scenario where user input can trigger frequent updates or API calls.

  • Versatile Application: Can be used in various scenarios beyond input fields, such as debouncing API calls, resize or scroll event handlers, and more.

  • Memory Leak Prevention: Cleans up timeouts on component unmount to prevent memory leaks, ensuring better resource management in React applications.

  • Refined User Experience: Enhances user experience by reducing the frequency of potentially disruptive or intensive operations during rapid user interactions.

  • Rate-limiting for User Actions: Useful for rate-limiting user actions, preventing excessive or unintended interactions, like rapid button clicks or toggle switches.

Usage

Here's an example of using useDebounce in a search input component:

import React, { useState } from 'react';
import { useDebounce } from '@custom-react-hooks/all';

const DebounceComponent = () => {
  const [inputValue, setInputValue] = useState('');
  const [debouncedValue, setDebouncedValue] = useState('');

  const [updateDebouncedValue] = useDebounce(
    (val) => {
      setDebouncedValue(val);
    },
    1000,
    { maxWait: 2000 },
  );

  const handleChange = (e) => {
    const value = e.target.value;
    setInputValue(value);
    updateDebouncedValue(value);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Type here..."
      />
      <p>Debounced Value: {debouncedValue}</p>
    </div>
  );
};

export default DebounceComponent;

In this component, the search function is debounced, which means it will only execute 500 milliseconds after the user stops typing.

API Reference

Parameters

  • callback (Function): The function to debounce.
  • delay (number): The number of milliseconds to delay.
  • options (object, optional): Configuration options for the debounce behavior. Options include:
    • maxWait (number): The maximum time the function can be delayed before it's executed, regardless of subsequent calls.
    • leading (boolean): If true, the function is executed on the leading edge of the timeout.
    • trailing (boolean): If true, the function is executed on the trailing edge of the timeout.

Returns

  • [debouncedFunction, cancelDebounce]:
    • debouncedFunction (Function): The debounced version of the provided function.
    • cancelDebounce (Function): A function that can be called to cancel the debounced action.

Use Cases

  • Search Input: Debounce search input to reduce the number of API calls during typing.
  • Form Validation: Delay validation until the user has stopped typing, improving performance and user experience.
  • Resize or Scroll Events: Improve performance by debouncing window resize or scroll event handlers.
  • Autocomplete Fields: Use in autocomplete or typeahead fields to control the rate of server requests.
  • Saving User Input: Auto-save user input in a text field or editor with a delay, reducing unnecessary save operations.
  • Rate-limiting User Actions: Prevent rapid, repeated actions by the user, like button clicks or toggle switches.

Notes

  • The useDebounce hook is useful for optimizing performance in scenarios where you want to limit the frequency of function execution.
  • Make sure to adjust the delay based on your specific use case.

Contributing

Your contributions are welcome! Feel free to submit issues or pull requests to improve the useDebounce hook.