1.0.5 • Published 4 years ago

@ccxvee/react-use-mounted v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

npm (scoped) David NPM npm

@ccxvee/react-use-mounted

React custom hook that allows to check whether a component is mounted or not.

Installation

npm install @ccxvee/react-use-mounted

Before usage

Probably you want to install this package to fix the next error: "Can't perform a React state update on an unmounted component". But first, try to make sure that this solution is perfect in your case. Who knows, maybe you'll find something better?

For example:

  • if you need to control requests, note to AbortController interface, which lets you cancel requests before a component unmounts instead of preventing the component state update after an unmount;
  • if you need to control timers or subscriptions, you can use a clean-up function inside the callback passed to useEffect;
  • and so on;

However, if alternative approaches don't solve your problem or an isMounted-pattern is more handy for you, feel free to use this package.

Usage

Note: isMounted is a ref object, so use isMounted.current to get a boolean value. Don't forget to include isMounted in a dependency array passed to useEffect if you need conditionally firing an effect.

import { useState, useEffect } from 'react';
import useMounted from "@ccxvee/react-use-mounted";

function MyComponent() {

  const [state, setState] = useState();
  const isMounted = useMounted();

  useEffect(() => {
  
    async function veryAsyncFunction() {
      /* some hidden actions */
    }
  
    veryAsyncFunction().then((data) => {
      if (isMounted.current) {
        setState(data);
      }
    });
    
  }, [isMounted]);
  
  return null;
}

Comparison with similar packages

There are many packages in npm that implement isMounted-pattern. However, the most popular of them have significant disadvantages.

Unlike these, @ccxvee/react-use-mounted have no dependencies at all and isMounted ref, returned by useMounted hook, do not affect your useEffect.

License

MIT License

1.0.5

4 years ago

1.0.4

4 years ago

1.0.2

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago