useIsMounted
A React hook that returns a function to check whether a component is currently mounted.
- Installation
- Add Source Code
npm install @plenty-hooks/use-is-mounted
npx @plenty-hooks/cli use-is-mounted
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
Showcase
import useIsMounted from '@plenty-hooks/use-is-mounted';
import { useState } from 'react';
function UserProfile({ userId }: { userId: string }) {
const isMounted = useIsMounted();
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUser = async () => {
setLoading(true);
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
// Only update state if component is still mounted
if (isMounted()) {
setUser(data);
setLoading(false);
}
};
fetchUser();
}, [userId, isMounted]);
if (loading) return <div>Loading...</div>;
return <div>{user?.name}</div>;
}
API
useIsMounted()
Returns a stable function that checks whether the component is currently mounted.
Returns
isMounted: () => boolean- A function that returnstrueif the component is mounted,falseotherwise