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

@teclone/react-use-effect-cleaner

v1.2.1

Published

Utility package for executing clean asynchronous stuffs in React use effect hook

Downloads

35

Readme

React Use Effect Cleaner

Familiar with the Can't perform a React state update on an unmounted component error? this tiny package is to help solve that as well prevent stalled state updates in react components.

Execution of asynchronous/scheduled calls such as setTimeout and setIntervals in React useEffect hook has some quite interesting gotchas. First is the possibility of running state updates even when the component had been unmounted.

Second is the possibility of running state updates from an effect that has already stalled, because you failed to clean the effect properly.

Third is unoptimization of network requests. Why make network requests when the effect is stalled?

Finally, these things can result to memory leaks, infinite loop/lifetime execution of code in client applications.

These three problems can be seen in the codebase below

import { useEffect, useState } from 'react';

// sample asynchronous request
const getUserProfile = (userId) => Promise.resolve({ id: userId });

const Profile = ({ userId }) => {
  const [user, setUser] = useState(0);

  useEffect(() => {
    getUserProfile(userId).then(setValue);
  }, [userId]);

  return (
    <div>
      <p>Userid: {user.id}</p>
    </div>
  );
};

If the Profile component gets unmounted, there is possibility that the call to get a user profile is still in progress, and would trigger a state update by the time it is resolved late in the application.

There is also a probability that the data of user A been shown as the data of user B.

Finally, could we abort a network request when the effect is no longer valid? for instance, when the userId changes or when the component gets unmounted

Installation

npm install @teclone/react-use-effect-cleaner

Sample Usage with Api Request Cleanup

Below is how to utilize this module to solve the problems of the code shown earlier.

import { useState, useEffect } from 'react';
import { createEffectCleaner } from '@teclone/react-use-effect-cleaner';

// sample asynchronous request
const getUserProfile = (userId, abortSignal) => Promise.resolve({ id: userId });

const Profile = ({ userId }) => {
  const [user, setUser] = useState(0);

  useEffect(() => {
    const abortController = new AbortController();
    const effects = createEffectCleaner(
      {
        setUser,
      },
      { abortController }
    );

    getUserProfile(userId, abortController.signal).then(effects.setUser);

    // return the cleaner
    return effects.clean();
  }, [userId]);

  return (
    <div>
      <p>Userid: {user.id}</p>
    </div>
  );
};

If the component is unmounted, or the userId changes, the effect cleaner will try to abort the request earlier. It will also prevent the setUser state change from executing.

The module utilizes the Proxy web api to create a middleware for all state modifiers.

AbortController is supported by popular request client libraries including Fetch and Axios.

Sample Usage with SetTimeout/SetInterval Cleanup

Below is an example of how to use the createEffectCleaner to clean up setTimeouts or setInterval.

import { useState, useEffect } from 'react';
import { createEffectCleaner } from '@teclone/react-use-effect-cleaner';

// sample asynchronous request
const getUserProfile = (userId, abortSignal) => Promise.resolve({ id: userId });

const Profile = ({ userId }) => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timoutIds = { count: 0 };
    const intervalIds = { count: 0 };

    // create effects
    const effects = createEffectCleaner(
      {
        setCount,
      },
      { timeoutIds, intervalIds }
    );

    timeoutIds.count = setTimeout(() => {
      effects.setCount((count) => count + 1);
    }, 10000);

    intervalIds.count = setInterval(() => {
      effects.setCount((count) => count + 1);
    }, 1000);

    // return the cleaner
    return effects.clean();
  }, [userId]);

  return (
    <div>
      <p>Current Count: {count}</p>
    </div>
  );
};

Interface

The package has only one export.

createEffectCleaner(stateModifiers, opts?)

  • stateModifiers: an object of stateModifiers that should be proxied.

  • opts: optional object with the following optional properties for cancelling or aborting networking/api requests

    • abortController - axios, fetch and others
    • cancelTokenSource - provide if your networking client is legacy axios
    • timeoutIds - an object store containing timeout ids from setTimeout. Note that the object must be treated as a store and modifications to the timoutIds must be made on the store for this to work. (pass by reference).
    • intervalIds - an object store containing interval ids from setInterval. Just like timeoutIds, the ids must be passed by reference.