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

Observe not always working when ref only is rendered after useIntersectionObserver #9

Open
fabb opened this issue Mar 16, 2020 · 3 comments

Comments

@fabb
Copy link

fabb commented Mar 16, 2020

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 visibilityTrackingRef after the component has been rendered (makes sense), and such also after useIntersectionObserver 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?

@fabb
Copy link
Author

fabb commented Mar 16, 2020

Maybe something like this would work, but it looks too complicated:

const lastRefRef = useRef<Element | null>(null)
const lastElementRef = useRef<Element | null>(null)
const lastIntersectObsRef = useRef<IntersectionObserver | null>(null)

useEffect(() => {
      const shouldExecute =
          lastIntersectObsRef.current !== intersectObs ||
          lastElementRef.current !== element ||
          lastRefRef.current !== ref.current
      lastIntersectObsRef.current = intersectObs
      lastRefRef.current = ref.current
      lastElementRef.current = element

      if (!shouldExecute) {
          return
      }

  if (!intersectObs) return

  let domNode

  if (ref) domNode = ref.current
  else if (element) domNode = element

  if (domNode) intersectObs.observe(domNode)

      return () => {
          if (!shouldExecute) {
              return
          }

          intersectObs.disconnect()
      }
}) // no dependency list here on purpose

Edit: Nah, that can‘t work, the logic in the unmount closure makes no sense. This would disconnect when nothing changes.

@fabb
Copy link
Author

fabb commented Mar 16, 2020

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)

@fabb
Copy link
Author

fabb commented Mar 17, 2020

Here is a blog post about this exact error: https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780

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

No branches or pull requests

1 participant