You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a problem when I render a div with the ref to be observed conditionally:
export const MyComponent = () => {
const [isLoading, setIsLoading] = useState<boolean>(true)
useEffect(() => {
async function fetchSimilarAds() {
setTimeout(() => {
setIsLoading(false)
}, 100)
}
// avoid showing old similar ads when client side paging through ads
setSearchResult(undefined)
fetchSimilarAds()
}, [])
const visibilityCallback = useCallback(() => {
console.log('visibilityCallback triggered') // BUG: never is triggered
}, [])
const visibilityTrackingRef = useRef<HTMLDivElement>(null)
useIntersectionObserver(visibilityTrackingRef, null, { triggerOnce: false, threshold: 0.7 }, visibilityCallback)
if (isLoading) {
return <Skeleton />
}
return (
<div ref={visibilityTrackingRef}>...content...</div>
}
I found that the problem is that React only sets the visibilityTrackingRefafter the component has been rendered (makes sense), and such also afteruseIntersectionObserver runs, while useEffect inside useIntersectionObserver would run after that, but because of the dependency array on useEffect ([ref, intersectObs, element]), it is skipped for the last render.
I don't really have an idea how to solve this without an additional useState in useIntersectionObserver which comes with the downside that it causes a rerender of MyComponent. Any suggestions?
The text was updated successfully, but these errors were encountered:
Dan Abramov wrote about using a „callback ref“ in this case, see this comment for the problem explanation and answers further below: facebook/react#14387 (comment)
I have a problem when I render a div with the
ref
to be observed conditionally:I found that the problem is that React only sets the
visibilityTrackingRef
after the component has been rendered (makes sense), and such also afteruseIntersectionObserver
runs, whileuseEffect
insideuseIntersectionObserver
would run after that, but because of the dependency array onuseEffect
([ref, intersectObs, element]
), it is skipped for the last render.I don't really have an idea how to solve this without an additional
useState
inuseIntersectionObserver
which comes with the downside that it causes a rerender ofMyComponent
. Any suggestions?The text was updated successfully, but these errors were encountered: