Skip to content

feat(useMeasure): support tracking an element via options.ref - #2719

Open
TT-Wang wants to merge 1 commit into
streamich:masterfrom
TT-Wang:use-measure-external-ref
Open

TT-Wang wants to merge 1 commit into
streamich:masterfrom
TT-Wang:use-measure-external-ref

Conversation

@TT-Wang

@TT-Wang TT-Wang commented Sep 11, 2026

Copy link
Copy Markdown

What

Adds an optional options.ref parameter to useMeasure. When provided, the hook observes ref.current instead of the element assigned to the callback ref it returns.

const myRef = useRef(null);
const { width, height } = useMeasure({ ref: myRef })[1];
return <div ref={myRef}>...</div>;

Why

Closes #1227. This has been requested by multiple users in that thread:

  • The returned callback ref is not a real useRef (no ref.current), so it cannot be combined with an existing ref.
  • Without this, an element that already has a ref cannot be measured.
  • It enables multiple useMeasure hooks in one component to track different elements.

The API is fully backward compatible: when options.ref is omitted, behavior is unchanged.

Notes

  • When ref.current changes, the layout effect re-runs and observes the new element (covered by a test).
  • Updated docs/useMeasure.md with the new usage.
  • All 7 tests in tests/useMeasure.test.ts pass, including 2 new ones covering the external-ref path.

Allow passing an existing ref through the new optional `options.ref`
parameter. When provided, the hook observes `ref.current` instead of
the element assigned to the callback ref it returns. This makes it
possible to measure an element that already has a ref, and to use
multiple useMeasure hooks in one component to track different elements.

Closes streamich#1227
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[useMeasure] Ability to track a custom Ref

1 participant