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

useElementState.ts

28 lines933 Bytes

1import { useRef, useState } from "react";
2​
3import { useStableCallback } from "./useStableCallback";
4​
5// Activity detaches refs while keeping DOM; retain hidden elements to avoid re-measuring on reveal.
6export function useElementState<T extends Element>(): readonly [
7 T | null,
8 (element: T | null) => void,
9] {
10 const [element, setElement] = useState<T | null>(null);
11 const latestRef = useRef<T | null>(null);
12 const setRef = useStableCallback((next: T | null) => {
13 if (next !== null) {
14 latestRef.current = next;
15 setElement(next);
16 return;
17 }
18 const previous = latestRef.current;
19 if (previous === null) return;
20 // A removed element is out of the document once the commit finishes.
21 queueMicrotask(() => {
22 if (latestRef.current !== previous || previous.isConnected) return;
23 latestRef.current = null;
24 setElement(null);
25 });
26 });
27 return [element, setRef] as const;