JAVASCRIPT
useIsMounted Hook to Track Component Mount Status
Create a simple `useIsMounted` React hook to safely determine if a component is currently mounted, preventing state updates on unmounted components.
import { useRef, useEffect, useState } from 'react';
const useIsMounted = () => {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true; // Component is mounted
return () => {
isMounted.current = false; // Component is unmounted
};
}, []); // Run only once on mount and cleanup on unmount
return isMounted; // Return the ref, not its current value
};
// Example Usage:
// import React, { useEffect, useState } from 'react';
// function DataFetcher() {
// const [data, setData] = useState(null);
// const isMounted = useIsMounted();
//
// useEffect(() => {
// const fetchData = async () => {
// // Simulate an async operation that takes time
// await new Promise(resolve => setTimeout(resolve, 2000));
// if (isMounted.current) { // Only update state if component is still mounted
// setData('Fetched data!');
// }
// };
// fetchData();
// }, [isMounted]);
//
// return (
// <div>
// {data ? <p>{data}</p> : <p>Loading...</p>}
// </div>
// );
// }
How it works: The `useIsMounted` hook utilizes `useRef` to create a mutable `isMounted` reference whose value persists across renders. Inside `useEffect` with an empty dependency array, `isMounted.current` is set to `true` when the component mounts and to `false` in the cleanup function when it unmounts. This allows components to safely perform asynchronous operations and only update state if the component is still mounted, preventing "Can't perform a React state update on an unmounted component" warnings and memory leaks.