MCPcopy Create free account
hub / github.com/nodejs/nodejs.org / useScrollToElement

Function useScrollToElement

apps/site/hooks/useScrollToElement.ts:11–45  ·  view source on GitHub ↗
(
  id: string,
  ref: RefObject<T | null>,
  debounceTime = 300
)

Source from the content-addressed store, hash-verified

9import useScroll from './useScroll';
10
11const useScrollToElement = <T extends HTMLElement>(
12 id: string,
13 ref: RefObject<T | null>,
14 debounceTime = 300
15) => {
16 const navigationState = use(NavigationStateContext);
17
18 // Restore scroll position on mount
19 useEffect(() => {
20 if (!ref.current) {
21 return;
22 }
23
24 // Restore scroll position if saved state exists
25 const savedState = navigationState[id];
26
27 // Scroll only if the saved position differs from current
28 if (savedState && savedState.y !== ref.current.scrollTop) {
29 ref.current.scroll({ top: savedState.y, behavior: 'auto' });
30 }
31 // navigationState is intentionally excluded
32 // it's a stable object reference that doesn't need to trigger re-runs
33 // eslint-disable-next-line @eslint-react/exhaustive-deps
34 }, [id, ref]);
35
36 // Save scroll position on scroll
37 const handleScroll = (position: { x: number; y: number }) => {
38 // Save the current scroll position in the navigation state
39 const state = navigationState as Record<string, { x: number; y: number }>;
40 state[id] = position;
41 };
42
43 // Use the useScroll hook to handle scroll events with debouncing
44 useScroll(ref, { debounceTime, onScroll: handleScroll });
45};
46
47export default useScrollToElement;

Callers 2

WithSidebarFunction · 0.85

Calls 1

useScrollFunction · 0.85

Tested by

no test coverage detected