JAVASCRIPT
Safely Handle Asynchronous Operations with a useIsMounted Hook
Develop a custom React hook to track if a component is currently mounted, preventing memory leaks and errors when performing asynchronous state updates.
import { useRef, useEffect } from 'react';
function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true; // Component has mounted
return () => {
isMounted.current = false; // Component is unmounting
};
}, []); // Empty dependency array means this effect runs once on mount and cleans up on unmount
return isMounted;
// Example Usage:
/*
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
const isComponentMounted = useIsMounted();
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
// Only update state if the component is still mounted
if (isComponentMounted.current) {
setData(result);
}
};
fetchData();
}, [isComponentMounted]);
return <div>{data ? <p>{JSON.stringify(data)}</p> : <p>Loading...</p>}</div>;
}
*/
}
How it works: The `useIsMounted` hook helps prevent "Can't perform a React state update on an unmounted component" warnings and potential memory leaks during asynchronous operations. It uses a `useRef` to maintain a mutable `isMounted.current` value, which is set to `true` when the component mounts and `false` during cleanup when it unmounts. This allows you to conditionally update state only if the component is still active.