🚀 Socket Launch Week 🚀 Day 5: Introducing Socket Fix.Learn More
Socket
Sign inDemoInstall
Socket

use-current-effect

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-current-effect

useEffect hook with injected current flag

1.1.2
Source
npm
Version published
Weekly downloads
32K
17.16%
Maintainers
1
Weekly downloads
 
Created
Source

useCurrentEffect

Sometimes we need to track if an effect has been cleaned up, because one of it's dependencies has changed, or the component was unmounted. The useCurrentEffect hook gives us a helper parameter to track this state without the usual boilerplate.

Installation

npm i use-current-effect or just copy the hook from this repo

Motivation

Dan Abramov shows us how we can track if the effect has been "cancelled" here https://overreacted.io/a-complete-guide-to-useeffect/#speaking-of-race-conditions

useEffect(() => {
  let didCancel = false;

  async function fetchData() {
    const article = await API.fetchArticle(id);
    if (!didCancel) {
      setArticle(article);
    }
  }

  fetchData();

  return () => {
    didCancel = true;
  };
}, [id]);

With useCurrentEffect you can do away with this boilerplate and clean up your effects...

useCurrentEffect((effectState) => {
  async function fetchData() {
    const article = await API.fetchArticle(id);
    if (effectState.isCurrent) {
      setArticle(article);
    }
  }

  fetchData();
}, [id]);

Any regular clean up function returned by the first effect parameter function will still be called after the ìsCurrent flag has been set, so you may still unsubscribe from subscriptions, or do other cleanup as usual.

Note that deconstructing the parameter as ({ isCurrent }) will cause issues, because doing so effectively creates a copy of boolean field, scoped to the effect function only, which will not be mutated by the cleanup.

ESLint

If you use the ESLint rule react-hooks/exhaustive-deps then you can add the useCurrentEffect to your additionalHooks Regex in your .eslint to ensure that you don't miss any dependencies.

"react-hooks/exhaustive-deps": ["warn", { "additionalHooks": "useCurrentEffect" }],

FAQs

Package last updated on 05 Sep 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts