Closed jdpt0 closed 9 months ago
This is just because the dependency array in the useEffect in useIntersectionObserver
is using the ref instead of ref.current. I just ran into this and changed the dependency array and it works as expected now. I will submit a PR in a bit.
This still seems to be a problem for me even after the fix that changes the dep array for useIntersectionObserver
to elementRef?.current
.
I have too this issue, seem a problem related with react 18 (and Next ? I use SSR), not sure. The ref is lost. It works on a page and not in anothers, I need to investigate more to understand the issue ...
I think I see the issue. The hook has a deps array with elementRef.current
. The problem is due to React's lifecycle, which happens in this order:
ref.current
to the new DOM nodesuseEffect
'So, when we use elementRef.current
inside the deps array (during render
time), it's always going to be the previous value, not the new value.
This means that if we hide an element, then we show it, the dependency array will still contain null
, and won't re-run the useEffect
. This can also happen when the ref
changes to a new DOM node.
Other libs (eg. react-intersection-observer
linked above) solve this by exporting a ref
callback, so that they're notified every time the ref
is updated. This is a very different API than the "passing in a ref" approach, but it works well.
Hi, thanks for the feedback! I've pushed a PR that should fix it, feel free to give a code review on it. See #464
@juliencrn I can confirm that is still not working as expected in 3.1.0.
If the observed element is conditionally rendered (rendered -> not rendered -> rendered) it simply stops working. Even the onResize
option fnc stops firing.
Please consider fixing this again :)
Thank you
In the below example I'm passing in an infinite react-query hook into this component to load more results once the bottom of the list has been reached. With
useIntersectionObserver
this happens the first time, but after that, the binding is lost and theLoad more
button has to be clicked to initiate the fetching of the query. Tested on React 17 and works as expected.A better pattern might be to pass a ref from the hook to bind to a specific component, as is done here.