Skip to content

m-avagyan/is-mounted-hook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

React hook for checking if the component is mounted.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published