DOMIntermediateSSR-safehooks/dom/useElementPosition.ts

useElementPosition

Element position in the viewport.

Import

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

API

Signature

useElementPosition(ref) → position

When to use

Use useElementPosition 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 · useElementPosition
Editor
function Pos() {
  const ref = useRef<HTMLDivElement>(null);
  const pos = useElementPosition(ref);
  return <div ref={ref}>{pos.top}, {pos.left}</div>;
}
Preview

Implementation source

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

hooks/dom/useElementPosition.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';
import { useResizeObserver } from './useResizeObserver';

export interface ElementPosition {
  top: number;
  left: number;
  right: number;
  bottom: number;
  width: number;
  height: number;
}

/** Tracks element position relative to the viewport. */
export function useElementPosition<T extends HTMLElement>(
  ref: RefObject<T | null>,
): ElementPosition {
  const [pos, setPos] = useState<ElementPosition>({
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    width: 0,
    height: 0,
  });

  const update = useCallback(() => {
    if (!isBrowser() || !ref.current) return;
    const r = ref.current.getBoundingClientRect();
    setPos({
      top: r.top,
      left: r.left,
      right: r.right,
      bottom: r.bottom,
      width: r.width,
      height: r.height,
    });
  }, [ref]);

  useIsomorphicLayoutEffect(() => {
    update();
  }, [update]);
  useEventListener('scroll', update, undefined, { passive: true });
  useEventListener('resize', update);
  useResizeObserver(ref, update);

  return pos;
}

Copy-paste example

useElementPosition.example.tsx
'use client';

import { useRef } from 'react';
import { useElementPosition } from '@/hooks';

export function Pos() {
  const ref = useRef<HTMLDivElement>(null);
  const pos = useElementPosition(ref);
  return <div ref={ref}>{pos.top}, {pos.left}</div>;
}

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/useElementPosition.ts for implementation details