Skip to main content

useIsMounted

A React hook that returns a function to check whether a component is currently mounted.

React 19.2.0
npm install @plenty-hooks/use-is-mounted

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 returns true if the component is mounted, false otherwise