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

use-cleanup-callback

v1.3.0

Published

React hook that is a hybrid of useCallback and the cleanup from useEffect

Downloads

139

Readme

use-cleanup-callback

version Build Status codecov

A react hook that utilizes the 'cleanup callback' pattern of useEffect within a 'useCallback' style hook.

codesandbox demo

Features

  • Provides a memoized callback that will update only if a dependency in the provided dependency array changes (same as useCallback).
  • Supports a cleanup callback within the provided callback which will be executed on the next successive function call, and/or on unmount.
  • Full Typescript support

The features can be thought of as either "useEffect which is called manually", or "useCallback with useEffect's cleanup pattern".

Installation

npm i use-cleanup-callback

Usage

import useCleanupCallback from 'use-cleanup-callback';

...

// within a component
const sayHiSoon = useCleanupCallback(() => {
  const timeoutId = setTimeout(() => {
    alert("Hello world!");
    console.log("Hello world!");
  }, 1000);

  return () => {
    clearTimeout(timeoutId);
  };
}, []);

return <button onClick={sayHiSoon}>Say hi</button>;

In the example above, clicking the button will start a timeout to log 'Hello world!' after 1000ms. If the button is clicked again before then, the timeout will be cleared, and a new timeout will be started. On unmount, the latest timeout will also be cleared.

Note: This is a custom hook that makes use of a dependencies array. It is recommended that you add this hook to your eslint config for the react-hooks/exhaustive-deps rule to warn about incorrect dependencies.

https://www.npmjs.com/package/eslint-plugin-react-hooks#advanced-configuration

{
  "rules": {
    // ...
    "react-hooks/exhaustive-deps": ["warn", {
      "additionalHooks": "useCleanupCallback"
    }]
  }
}

Advanced Usage

The callback you provide to the hook typically will return a 'cleanup' callback like so:

const greetAndAlert = useCleanupCallback((foo) => {
  const calculatedResult = 'hello ' + foo;
  const timeoutId = setTimeout(() => {
    alert(calculatedResult);
  }, 1000)
  ...

  // cleanup callback:
  return () => {
    clearTimeout(timeoutId);
  }
}, []);

This means that when you later call the function, you don't get a meaningful return value to use for yourself.

const result = greetAndAlert("world");
// `result` will just be the cleanup callback here!

While not anticipated to be a common use case, in order to both return a value and use a cleanup callback, you can use object notation for the return value in the following shape:

{
  value: unknown;
  cleanup: () => void
}

For example:

const greetAndAlert = useCleanupCallback((foo) => {
  const calculatedResult = 'hello ' + foo;
  const timeoutId = setTimeout(() => {
    alert(calculatedResult);
  }, 1000)
  ...

  // object notation return:
  return {
    value: calculatedResult,
    cleanup: () => {
      clearTimeout(timeoutId);
    }
  }
})
const result = greetAndAlert("world");
// result === 'hello world'
// `result` is returned here, *and* we still get to use the cleanup!

Options

useCleanupCallback takes an optional object as a third argument to pass additional options to in order to customize the behaviour of the hook.

| Name | Type | Default | Description | |---------------------|---------|---------|----------------------------------------------------------------------------------| | cleanUpOnCall | boolean | true | Whether to call the last cleanup when the output callback of the hook is called. | | cleanUpOnDepsChange | boolean | false | Whether to call the last cleanup when dependencies change. | | cleanUpOnUnmount | boolean | true | Whether to call the last cleanup when the hook unmounts. |

Limitations

  • Similarly to useEffect, the callback and returned cleanup callback must be synchronous (i.e. an async function callback will not work). You can alleviate this the same way you would with useEffect by defining the asynchronous function within the callback, and calling it immediately.

    const fetchTodo = useCleanupCallback(() => {
      const controller = new AbortController();
      async function handleCallback() {
        try {
          const res = await fetch(
            "https://jsonplaceholder.typicode.com/todos/1",
            {
              signal: controller.signal,
            }
          );
          const data = await res.json();
          // do stuff with data
        } catch (err) {
          if (err.name === "AbortError") return;
          // handle error
          console.error("An unknown error has occurred: ", err);
        }
      }
      // call the async function immediately within this callback
      handleCallback();
    
      return () => {
        // on cleanup, abort the controller for this scope
        controller.abort();
      };
    }, []);

    codesandbox async example