@ubuligan/use-is-mounted-hook
v1.0.7
Published
A lightweight React hook that tells whether a component is still mounted.
Maintainers
Readme
useIsMounted Hook
A lightweight React hook that tells whether a component is still mounted.
Installation
npm install @ubuligan/use-is-mounted-hookor with yarn:
yarn add @ubuligan/use-is-mounted-hookor with pnpm:
pnpm add @ubuligan/use-is-mounted-hookUsage
import { useIsMounted } from '@ubuligan/use-is-mounted-hook';
function MyComponent() {
const isMounted = useIsMounted();
useEffect(() => {
fetchData().then(() => {
if (isMounted.current) {
// Component is still mounted, safe to update state
setData(result);
}
});
}, []);
return <div>My Component</div>;
}API
useIsMounted()
Returns a ref object with a current property that indicates whether the component is mounted.
Returns:
React.MutableRefObject<boolean>- A ref object wherecurrentistrueif the component is mounted,falseotherwise.
Use Cases
This hook is useful for preventing memory leaks and avoiding state updates on unmounted components. Common scenarios include:
- Async operations (API calls, timers) that complete after component unmount
- Preventing "Can't perform a React state update on an unmounted component" warnings
- Conditional state updates based on component mount status
Example
import { useIsMounted } from '@ubuligan/use-is-mounted-hook';
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const isMounted = useIsMounted();
useEffect(() => {
let cancelled = false;
const fetchUser = async () => {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
if (isMounted.current && !cancelled) {
setUser(data);
}
} catch (error) {
if (isMounted.current && !cancelled) {
console.error('Failed to fetch user:', error);
}
} finally {
if (isMounted.current && !cancelled) {
setLoading(false);
}
}
};
fetchUser();
return () => {
cancelled = true;
};
}, [userId, isMounted]);
if (loading) return <div>Loading...</div>;
if (!user) return <div>User not found</div>;
return <div>{user.name}</div>;
}Requirements
- React 16.8.0 or higher (requires hooks support)
License
MIT
Author
Ubuligan
