The "onResize" callback doesn't work correctly with conditional rendering
See original GitHub issueI’m using the library with onResize
callback because I need to use another reference to DOM element to set width, but I have an issue when the component uses “loading status” so component with associated ref
is conditionally rendered.
return (
<>
{displayLoader ? (
<LoadingBar />
) : (
<Grid ref={measuredBoxRef}>...</Grid>
)}
</>
)
In the library is a dependency for ref
in the useEffect
hook so when loading state is changed and component is rendered the ResizeObserver doesn’t observe this element because the ref
is not completely changed (only current
value). This problem is described on pages:
https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780
https://dev.to/fnky/pitfalls-of-conditional-rendering-and-refs-in-react-29oi
I can’t separate the component like it is proposed in second article, so I’m trying to change the library to use useCallback
hook.
Perhaps you met with this problem and you have another solution?
I know that issue is specified for my code but ref
in dependencies is not recommended practice and even on the React page is an example to measure DOM element with useCallback
hook: https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (6 by maintainers)
Yeah so the
useCallback
hook is not even the interesting part there, but rather supporting callback refs, so that the observer hook would receive the new ref as React provides it.Not sure what it would look like though…
Maybe something like this?
Then whenever a new node is provided, the hook would trigger the same effect it currently does when the ref instance changes.
Could work.
callback refs are now live in the latest release: https://github.com/ZeeCoder/use-resize-observer/releases/tag/v6.2.0-alpha.1
Also see the documentation: https://github.com/ZeeCoder/use-resize-observer#observing-components-mounted-with-a-delay