-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathuseScrollToElement.ts
More file actions
47 lines (36 loc) · 1.42 KB
/
useScrollToElement.ts
File metadata and controls
47 lines (36 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use client';
import { useContext, useEffect } from 'react';
import { NavigationStateContext } from '#site/providers/navigationStateProvider';
import type { RefObject } from 'react';
import useScroll from './useScroll';
const useScrollToElement = <T extends HTMLElement>(
id: string,
ref: RefObject<T | null>,
debounceTime = 300
) => {
const navigationState = useContext(NavigationStateContext);
// Restore scroll position on mount
useEffect(() => {
if (!ref.current) {
return;
}
// Restore scroll position if saved state exists
const savedState = navigationState[id];
// Scroll only if the saved position differs from current
if (savedState && savedState.y !== ref.current.scrollTop) {
ref.current.scroll({ top: savedState.y, behavior: 'auto' });
}
// navigationState is intentionally excluded
// it's a stable object reference that doesn't need to trigger re-runs
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, ref]);
// Save scroll position on scroll
const handleScroll = (position: { x: number; y: number }) => {
// Save the current scroll position in the navigation state
const state = navigationState as Record<string, { x: number; y: number }>;
state[id] = position;
};
// Use the useScroll hook to handle scroll events with debouncing
useScroll(ref, { debounceTime, onScroll: handleScroll });
};
export default useScrollToElement;