mediumRace ConditionsReact
The unmounted update
A developer asked an AI assistant to fetch a user's profile when a modal opens and show a loading spinner until it resolves. The suggested code works fine when the modal stays open, but throws a console warning, and occasionally a real bug, when a user closes the modal before the fetch finishes.
ProfileModal.jsx
function ProfileModal({ userId, onClose }) {
const [profile, setProfile] = useState(null);
useEffect(() => {
fetchProfile(userId).then((data) => {
setProfile(data);
});
}, [userId]);
if (!profile) return <Spinner />;
return <ProfileCard profile={profile} onClose={onClose} />;
}What happens if the user closes the modal, unmounting ProfileModal, before fetchProfile resolves?
setProfile still runs on the unmounted component when the promise resolves — React warns about updating state on an unmounted component, and related side effects can fire unexpectedly.
fetchProfile is automatically cancelled the instant the component unmounts.
The useEffect cleanup function throws because userId is no longer defined.
Nothing happens — React silently ignores all state updates from components that no longer exist.