1import { UIEvent, useCallback, useEffect, useRef } from 'react';
2
3/** The list of persisted scroll positions, by id */
4const scrollPositions: Record<string, number> = {};
5
6/**
7 * Keep track and restore the scroll position when changing page.
8 * The ID is used to identify the stored scroll position.
9 */
10export function usePersistScroll<T extends HTMLElement = HTMLDivElement>(id: string) {
11  const ref = useRef<T>(null);
12
13  const onScroll = useCallback((event: UIEvent<T>) => {
14    scrollPositions[id] = event.currentTarget.scrollTop;
15  }, []);
16
17  useEffect(
18    function scrollRefDidMount() {
19      if (ref.current && scrollPositions[id] > 0) {
20        ref.current.scrollTop = scrollPositions[id];
21      }
22    },
23    [ref.current]
24  );
25
26  return { ref, onScroll };
27}
28