Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve internal useElementSize hook by computing the size as soon as possible #3153

Merged
merged 1 commit into from Apr 30, 2024

Conversation

RobinMalfait
Copy link
Collaborator

@RobinMalfait RobinMalfait commented Apr 30, 2024

This PR improves the useElementSize hook by ensuring that the size of an element is calculated as soon as possible.

Instead of waiting for a useEffect to trigger, we can use useMemo to always compute the size the moment a DOM element is available (or changes).

Once a DOM node is stable, we also setup a ResizeObserver to watch for changes. If we detect a resize, we simply force a re-render which also forces the useMemo to recompute. This way we can always rely on the useMemo to be the single source of truth without managing state ourselves.

Before:
image
Notice how the second log has an input DOM element present, but the --button-width is still at 0px

After:
image
Notice how the second log is the first log where the input DOM element is present, and the --button-width is immediately the correct value.

Instead of waiting for a `useEffect` to trigger, we can use `useMemo` to
always compute the size the moment a DOM element is available (or
changes).

We also make sure to force a re-render when resizes are detected on the
stable DOM node, which in turn causes the `useMemo` to recompute.
Copy link

vercel bot commented Apr 30, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
headlessui-react ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 30, 2024 10:37am
headlessui-vue ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 30, 2024 10:37am

@RobinMalfait RobinMalfait merged commit f35214d into main Apr 30, 2024
8 checks passed
@RobinMalfait RobinMalfait deleted the fix/combobox-demo-mode-flicker branch April 30, 2024 17:31
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.

None yet

2 participants