Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useIntentTarget.ts

22 lines804 Bytes

1import { useRef, useState } from "react";
2​
3import { useStableCallback } from "~/hooks/useStableCallback";
4​
5const INTENT_DELAY_MS = 150;
6​
7export function useIntentTarget<Target>(isListed: (target: Target) => boolean) {
8 const [target, setTarget] = useState<Target | null>(null);
9 const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
10 // A removed row fires no leave event.
11 const listed = target !== null && isListed(target);
12 if (target !== null && !listed) setTarget(null);
13 const setIntent = useStableCallback((next: Target | null) => {
14 clearTimeout(timer.current);
15 if (next === null) {
16 setTarget(null);
17 return;
18 }
19 timer.current = setTimeout(() => setTarget(next), INTENT_DELAY_MS);
20 });
21 return [listed ? target : null, setIntent] as const;