Skip to content

Conversation

arichard-info
Copy link

@arichard-info arichard-info commented Sep 30, 2025

Description

Fix: Add element validation in useMeasure to prevent ResizeObserver crashes

Problem

The useMeasure hook can crash with TypeError: Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element' when the element ref contains unexpected values instead of valid DOM elements.

This commonly occurs in scenarios involving:

  • Dynamic imports with Next.js that may fail and return retry objects {retry: function}
  • Lazy loading components where refs are populated before actual DOM elements are ready
  • SSR/hydration mismatches
  • Bad use of ref

Root Cause

The current implementation only checks for truthiness (if (!element)) but doesn't validate that the element is actually a valid DOM element before calling ResizeObserver.observe(element).

Solution

Added a type check typeof element.getBoundingClientRect !== "function" to ensure the element has the necessary DOM methods before attempting to observe it.

Benefits

  • ✅ Prevents crashes when refs contain non-DOM objects
  • ✅ Maintains backward compatibility
  • ✅ Minimal performance impact
  • ✅ Graceful degradation - hook simply won't observe invalid elements

Testing

Tested with Next.js dynamic imports where refs temporarily contain retry objects instead of DOM
elements.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as before)

Checklist

  • Read the Contributing Guide
  • Perform a code self-review
  • Comment the code, particularly in hard-to-understand areas
  • Add documentation
  • Add hook's story at Storybook
  • Cover changes with tests
  • Ensure the test suite passes (yarn test)
  • Provide 100% tests coverage
  • Make sure code lints (yarn lint). Fix it with yarn lint:fix in case of failure.
  • Make sure types are fine (yarn lint:types).

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.

1 participant