All files / src/hooks useScrollToTop.ts

100% Statements 5/5
100% Branches 2/2
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23                        73x   73x 58x 8x   50x        
import { useEffect, RefObject } from 'react';
import { useLocation } from 'react-router-dom';
 
/**
 * Hook to scroll to top on route changes
 * Should be used in layout components to ensure scroll restoration
 * works consistently across all routes
 *
 * @param containerRef - Optional ref to a scrollable container element.
 *                       If provided, scrolls that element instead of window.
 */
export function useScrollToTop(containerRef?: RefObject<HTMLElement | null>) {
  const { pathname } = useLocation();
 
  useEffect(() => {
    if (containerRef?.current) {
      containerRef.current.scrollTo(0, 0);
    } else {
      window.scrollTo(0, 0);
    }
  }, [pathname, containerRef]);
}