is-mounted-hook
React hook for checking if the component is mounted.
Author
- name: Martik Avagyan
- email: martikavagyan1@gmail.com
- github: m-avagyan
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