Files
Tom Moor 4a2d36e2fa chore: Remove useIsMounted guards that only avoid the unmounted setState warning (#13843)
React 18+ no longer warns on setState after unmount, so the guards in
useRequest, useIdle, ActionButton, useDocumentSave and MultiplayerEditor are
removed. The Mentions guards protect an editor transaction against a destroyed
node view, so they are replaced with an effect-scoped cancel flag. Both
useIsMounted hook files are deleted.

Closes #13839
2026-09-21 22:37:27 -04:00

68 lines
1.6 KiB
TypeScript

import { throttle } from "es-toolkit/compat";
import { useState, useRef, useCallback, useEffect } from "react";
import { Minute } from "@shared/utils/time";
const activityEvents = [
"click",
"mousemove",
"keydown",
"DOMMouseScroll",
"mousewheel",
"mousedown",
"touchstart",
"touchmove",
"focus",
];
/**
* Hook to detect user idle state.
*
* @param timeToIdle The time in ms until idle
* @param events The events to listen to
* @returns boolean if the user is idle
*/
export default function useIdle(
timeToIdle: number = 3 * Minute.ms,
events = activityEvents
) {
const [isIdle, setIsIdle] = useState(false);
const timeout = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const onActivity = useCallback(() => {
if (timeout.current) {
clearTimeout(timeout.current);
}
timeout.current = setTimeout(() => {
setIsIdle(true);
}, timeToIdle);
}, [timeToIdle]);
useEffect(() => {
const handleUserActivityEvent = throttle(() => {
setIsIdle(false);
onActivity();
}, 1000);
events.forEach((eventName) =>
window.addEventListener(eventName, handleUserActivityEvent)
);
// Start the countdown immediately, otherwise the user is never considered
// idle unless activity occurs after mount.
onActivity();
return () => {
handleUserActivityEvent.cancel();
if (timeout.current) {
clearTimeout(timeout.current);
}
events.forEach((eventName) =>
window.removeEventListener(eventName, handleUserActivityEvent)
);
};
}, [events, onActivity]);
return isIdle;
}