a tool for shared writing and social publishing
at update/thread-viewer 23 lines 739 B view raw
1import { useRef, useEffect } from "react"; 2 3let scrollPositions: { [key: string]: number } = {}; 4export function usePreserveScroll<T extends HTMLElement>(key: string | null) { 5 let ref = useRef<T | null>(null); 6 useEffect(() => { 7 if (!ref.current || !key) return; 8 9 if (scrollPositions[key] !== undefined) 10 window.requestAnimationFrame(() => { 11 ref.current?.scrollTo({ top: scrollPositions[key] || 0 }); 12 }); 13 14 const listener = () => { 15 if (!ref.current?.scrollTop) return; 16 scrollPositions[key] = ref.current.scrollTop; 17 }; 18 19 ref.current.addEventListener("scroll", listener); 20 return () => ref.current?.removeEventListener("scroll", listener); 21 }, [key, ref.current]); 22 return { ref }; 23}