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

usetimeout-react-hook

v0.1.2

Published

React.js custom hook that sets a leak-safe timeout and returns a function to cancel it before the timeout expires.

Downloads

37,029

Readme

React.js custom hook that sets a leak-safe timeout and returns a function to cancel it before the timeout expires.

Install

npm install usetimeout-react-hook

🔑 Key features

  • 🥇 inspired by this awesome blog post by Dan Abramov
  • ⚠️ optional manual cancelability of timeout
  • ✨ uses useEffect dependencies array as a policy to dictate the hook updates, by default no dependency is specified
  • 💪 written in TypeScript
  • ✔️ 100% test coverage

🤔 Yet another setTimeout hook, why?

If you search something among the lines of react-use-timeout a number of results appear. Why was this package necessary?

Most of the other timeout hook packages I've glanced at had the following shortcomings:

  • stuck with setTimeout, with no generic timer support
  • no custom re-render policy
  • no tests in place

Sometimes user needs the ability to use a custom timer, since setTimeout may not always be the best choice, especially in React Native applications. In fact, the primary reason I built this custom hook was to expose a customizable and reusable timeout manager for an other package of mine, react-native-user-inactivity. A number of users had pointed out that on React Native there were the following issues with setTimeout:

  • it would cause a crash on Android after many minutes of timeout
  • it would simply stop working when the application is in background

Hopefully this package will be useful to others as well.

❔ How to use

This package exposes two hooks, useTimeoutDefault and useTimeout. Actually, the first one is just a wrapper for the second, and uses the standard setTimeout and clearTimeout as timeout handler methods. Since useTimeoutDefault is what many users probably need the most, it's the default exported package. Each of this hook return a single function, which can be optionally used to manually cancel the timeout before it expires. The type of this function, CancelTimer, is: () => void.

The signature of useTimeoutDefault is the following:

import useTimeoutDefault from 'usetimeout'; // notice that it's a default import

/**
 * useTimeoutDefault is a React.js custom hook that sets a leak-safe timeout and returns
 * a function to cancel it before the timeout expires.
 * It uses the default timeout handlers, i.e. window.setTimeout and window.clearTimeout.
 * It's composed of two other native hooks, useRef and useEffect.
 * If a new callback is given to the hook before the previous timeout expires,
 * only the new callback will be executed at the moment the timeout expires.
 * When the hook receives a new callback, the timeout isn't reset.
 * 
 * @param callback the function to be executed after the timeout expires
 * @param timeout the number of milliseconds after which the callback should be triggered
 * @param deps useEffect dependencies that should cause the timeout to be reset
 * @return function to cancel the timer before the timeout expires
 */
type UseTimeoutDefault = (callback: () => void, timeout: number, deps?: unknown[]) => CancelTimer;

Since usetimeout supports a generic timer, it requires an implementation of the TimeoutHandler interface, which is defined as:

interface TimeoutHandler<T> {
  /**
   * Timeout function that accepts two parameters:
   * a function and the timeout after which that function is fired.
   * If not provided, the default `setTimeout` implementation will be
   * the standard `window.setTimeout`.
   */
  setTimeout: (fn: () => void, timeout: number) => T;

  /**
   * Function that should be used to clear the effects of `setTimeout` after
   * the component where it is rendered is unmounted.
   * If not provided, the default `clearTimeout` implementation will be
   * the standard `window.clearTimeout`.
   */
  clearTimeout: (timeout: T | undefined) => void;
}

The signature of useTimeout is the following:

import { useTimeout } from 'usetimeout'; // notice that it's a named import

/**
 * useTimeout is a React.js custom hook that sets a leak-safe timeout and returns
 * a function to cancel it before the timeout expires.
 * It's composed of two other native hooks, useRef and useEffect.
 * It requires a custom way of setting a timeout and clearing it, expressed as an implementation
 * of the generic TimeoutHandler<T> interface.
 * The timer is restarted every time an item in `deps` changes.
 * If a new callback is given to the hook before the previous timeout expires,
 * only the new callback will be executed at the moment the timeout expires.
 * When the hook receives a new callback, the timeout isn't reset.
 * 
 * @param callback the function to be executed after the timeout expires
 * @param timeout the number of milliseconds after which the callback should be triggered
 * @param timeHandler TimeoutHandler instance that's used to set and clear the timeout
 * @param deps useEffect dependencies that should cause the timeout to be reset
 * @return function to cancel the timer before the timeout expires
 */
type UseTimeout = <T>(callback: () => void, timeout: number, timeHandler: TimeoutHandler<T>, deps?: unknown[]) => CancelTimer;

✔️ Run tests

Tests are run using jest, at the end of the test a coverage table should appear.

npm run test

🚀 Build package

This package is built using TypeScript, so the source needs to be converted in JavaScript before being usable by the users. usetimeout uses Rollup as build system, and the JavaScript module formats it's been configured to support are:

  • CommonJS: module format used by Node (using require function).
  • ESM: modern module format (using import syntax).
  • UMD: Universal Module Definition, to be able to import it directly in the browser (not as popular these days).
npm run build

👤 Author

Alberto Schiabel

🤝 Contributing

Contributions, issues and feature requests are welcome!Feel free to check issues page. The code is short, throughly commented and well tested, so you should feel quite comfortable working on it. If you have any doubt or suggestion, please open an issue.

🦄 Show your support

Give a ⭐️ if this project helped or inspired you!

📝 License

Built with ❤️ by Alberto Schiabel. This project is MIT licensed.

Related packages