Improve internal useElementSize
hook by computing the size as soon as possible
#3153
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 useuseMemo
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 theuseMemo
to recompute. This way we can always rely on theuseMemo
to be the single source of truth without managing state ourselves.Before:
Notice how the second log has an
input
DOM element present, but the--button-width
is still at0px
After:
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.