a tool for shared writing and social publishing
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 window.requestAnimationFrame(() => {
10 ref.current?.scrollTo({ top: scrollPositions[key] || 0 });
11 });
12
13 const listener = () => {
14 if (!ref.current?.scrollTop) return;
15 scrollPositions[key] = ref.current.scrollTop;
16 };
17
18 ref.current.addEventListener("scroll", listener);
19 return () => ref.current?.removeEventListener("scroll", listener);
20 }, [key, ref.current]);
21 return { ref };
22}