Mark a component mounted in a layout effect

useIsMountedRef set its ref in a passive effect, which React runs some time
after the commit. In between, the component is in the DOM and can be clicked
while the ref still says it is not mounted, and useToggle drops the click.
The Accounts page showed it: an "Account" click right after the page drew
did not open the create modal. Under load in a spec this happened in one
run out of five. A layout effect runs during the commit, before an event can
reach the component; unmounting still clears the ref.
This commit is contained in:
Satoshi Qazi Muhammed authored and SatoshiQaziMuhammed committed 2026-10-12 01:46:05 +04:00
1 parent ab2eb5f80a
commit 676780874a
1 file changed
+5 -2
+5 -2
View File
@@ -3,7 +3,7 @@
import type React from 'react';
import { useEffect, useRef } from 'react';
import { useLayoutEffect, useRef } from 'react';
import { createNamedHook } from './createNamedHook.js';
@@ -12,7 +12,10 @@ export type MountedRef = React.MutableRefObject<boolean>;
function useIsMountedRefImpl (): MountedRef {
const isMounted = useRef(false);
useEffect((): () => void => {
// A layout effect runs while the component is committed, before the browser
// can deliver an event to it. A passive effect runs later, so a click that
// lands in between found the ref still false and was dropped.
useLayoutEffect((): () => void => {
isMounted.current = true;
return (): void => {