Refs in useEffect: Tracking Component Lifecycle
What you'll learn: How to use a ref to track whether a component is still mounted, preventing bugs from asynchronous operations that try to update state after unmount.
The Problem: Async Operations and Unmounted Components
You've learned that refs survive re-renders and don't trigger re-renders when changed. This makes them perfect for tracking whether your component is still alive.
When you start an async operation (like a timer or fetch) inside useEffect, the component might unmount before that operation completes. If you try to call setState after unmount, React will warn you about memory leaks.
The Solution: An isMounted Ref
Think of a ref as a little flag you plant when the component mounts. You check this flag before updating state in async callbacks:
function DataDisplay() {
const [data, setData] = useState(null);
const isMountedRef = useRef(true);
useEffect(() => {
isMountedRef.current = true;
setTimeout(() => {
// Only update state if component is still mounted
if (isMountedRef.current) {
setData('Loaded!');
}
}, 2000);
return () => {
// Cleanup: mark as unmounted
isMountedRef.current = false;
};
}, []);
return <div>{data}</div>;
}
Why This Works
The ref acts like a guardian at the gate. When the cleanup function runs (component unmounts), it sets the flag to false. The async callback checks the flag before calling setData, preventing the "Can't perform a React state update on an unmounted component" warning.
Key Takeaway: Use a ref set to true on mount and false in cleanup to safely guard async state updates in effects, preventing attempts to update unmounted components.