is-mounted-hook
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

is-mounted-hook

React hook for checking if the component is mounted.

Author

Getting started

Installation

npm install is-mounted-hook or yarn add is-mounted-hook

Example

import React, { useState, useEffect } from 'react';
import useIsMounted from 'is-mounted-hook';

import { getCars } from '../../services/cars';

import Loader from '../loader/Loader';
import Error from '../error/Error';
import CarList from '../car-list/CarList';

function Example() {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [data, setData] = useState(null);

  const isMounted = useIsMounted();

  useEffect(() => {
    getCars()
      .catch((error) => setError(error.message))
      .then((data) => {
        if (!isMounted.current) {
          return;
        }

        setData(data);
      })
      .finally(() => setIsLoading(false));
  }, []);

  return isLoading ? (
    <Loader />
  ) : error ? (
    <Error message={error} />
  ) : (
    <CarList data={data} />
  );
}

export default Example;

Copyright (c) 2022 Martik Avagyan

Dependents (0)

Package Sidebar

Install

npm i is-mounted-hook

Weekly Downloads

2

Version

1.2.0

License

MIT

Unpacked Size

4.97 kB

Total Files

6

Last publish

Collaborators

  • m-avagyan