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

[BUG] useIntersectionObserver loses ref node access since v3 #616

Closed
tengweiherr opened this issue Jul 16, 2024 · 0 comments
Closed

[BUG] useIntersectionObserver loses ref node access since v3 #616

tengweiherr opened this issue Jul 16, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@tengweiherr
Copy link

tengweiherr commented Jul 16, 2024

Describe the bug

Since the breaking change in the useIntersectionObserver hook in v2.13.0, we no longer have to pass a ref to the hook. Instead, it exports the callback ref for us to bind to the DOM node. I understand that the reason behind the change is to address the issue described here. However, using the callback ref loses the ref node access at the same time.

To Reproduce

We have a use case where we track the position of a div container and only render its children when the container enters the viewport. (I believe this optimization technique is called above-the-fold).

This custom hook was built on top of the useIntersectionObserver hook before v2.13.0

export const useInViewOnce = () => {
  const ref = useRef(null)

  const entry = useIntersectionObserver(ref, {
    rootMargin: `0px 0px`,
    freezeOnceVisible: true,
  })

  const isVisible = !!entry?.isIntersecting

  useEffect(() => {
    if (!ref.current) return
    ref.current.style.height = isVisible ? 'auto' : `500px`
  }, [isVisible])

  return { ref, hasEnteredView: isVisible }
}

Use case

const { ref, hasEnteredView } = useInViewOnce<HTMLDivElement>()

<div ref={ref}>
    {hasEnteredView && <ChildrenComponents />}
</div>

The same function is not achievable with the latest version of usehooks-ts as we lose access to the ref node

Expected behavior

It provides us access to the ref node in the onChange callback function

Additional context

Since the intention here is to have some side effects on the ref node itself when it is intersecting, I recommend passing the ref node in the onChange callback so we can have access to the reference node properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant