DOMIntermediateSSR-safehooks/dom/useScrollPosition.ts

useScrollPosition

Alias of useScroll.

Import

TypeScript
import { useScrollPosition } from '@/hooks';

API

Signature

useScrollPosition(ref?) → { x, y }

When to use

Use useScrollPosition 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 · useScrollPosition
Editor
function Y() {
  const { y } = useScrollPosition();
  return <p>{y}</p>;
}
Preview

Implementation source

Full library source for useScrollPosition — copy into your project when you are not installing a package yet.

hooks/dom/useScrollPosition.ts
import { useScroll } from './useScroll';
import type { RefObject } from 'react';

/** Alias of {@link useScroll}. */
export function useScrollPosition<T extends HTMLElement>(
  ref?: RefObject<T | null>,
) {
  return useScroll(ref);
}

Copy-paste example

useScrollPosition.example.tsx
'use client';

import { useScrollPosition } from '@/hooks';

export function Y() {
  const { y } = useScrollPosition();
  return <p>{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/useScrollPosition.ts for implementation details