useScroll
Window or element scroll x/y.
Import
TypeScript
import { useScroll } from '@/hooks';API
Signature
useScroll(ref?) → { x, y }
When to use
Use useScroll instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Measurements are 0 / empty until the element is mounted.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useScrollEditor
function ScrollPos() { const { x, y } = useScroll(); return <p>scroll {x},{y}</p>; }
Preview
Implementation source
Full library source for useScroll — copy into your project when you are not installing a package yet.
hooks/dom/useScroll.ts
import { useCallback, useState } from 'react';
import type { RefObject } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useEventListener } from '../events/useEventListener';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
export interface ScrollState {
x: number;
y: number;
}
/**
* Scroll position for window or an element.
* Omit ref to track window scroll.
*/
export function useScroll<T extends HTMLElement>(
ref?: RefObject<T | null>,
): ScrollState {
const [scroll, setScroll] = useState<ScrollState>({ x: 0, y: 0 });
const update = useCallback(() => {
if (!isBrowser()) return;
if (ref?.current) {
setScroll({ x: ref.current.scrollLeft, y: ref.current.scrollTop });
} else {
setScroll({ x: window.scrollX, y: window.scrollY });
}
}, [ref]);
useIsomorphicLayoutEffect(() => {
update();
}, [update]);
useEventListener('scroll', update, ref ?? undefined, { passive: true });
useEventListener('scroll', update, undefined, {
passive: true,
enabled: !ref,
});
return scroll;
}
Copy-paste example
useScroll.example.tsx
'use client';
import { useScroll } from '@/hooks';
export function ScrollPos() {
const { x, y } = useScroll();
return <p>scroll {x},{y}</p>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Attach the ref before measuring. ResizeObserver requires a mounted element.
- Source of truth: open
hooks/dom/useScroll.tsfor implementation details