Skip to content

Commit

Permalink
refactor(use-intersection): remove useRef usage (#39791)
Browse files Browse the repository at this point in the history
The PR neither fixes a bug nor introduces a new feature. It just makes the current code be more clearer.

We track the `unobserve` method (to clear the side-effect) in a ref before this PR which is not required anymore:

- The `unobserve` method can only be created during the `useEffect`
- The `unobserve` method will be called during `useEffect` cleans up.

In short, the "life cycle" of the `unobserve` method now only lives inside the `useEffect`. So we can remove the usage of `useRef`.
  • Loading branch information
SukkaW committed Aug 21, 2022
1 parent 05b621a commit bf82a47
Showing 1 changed file with 3 additions and 12 deletions.
15 changes: 3 additions & 12 deletions packages/next/client/use-intersection.tsx
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import {
requestIdleCallback,
cancelIdleCallback,
Expand Down Expand Up @@ -100,30 +100,21 @@ export function useIntersection<T extends Element>({
}: UseIntersection): [(element: T | null) => void, boolean, () => void] {
const isDisabled: boolean = disabled || !hasIntersectionObserver

const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false)
const [element, setElement] = useState<T | null>(null)

useEffect(() => {
if (hasIntersectionObserver) {
if (unobserve.current) {
unobserve.current()
unobserve.current = undefined
}

if (isDisabled || visible) return

if (element && element.tagName) {
unobserve.current = observe(
const unobserve = observe(
element,
(isVisible) => isVisible && setVisible(isVisible),
{ root: rootRef?.current, rootMargin }
)
}

return () => {
unobserve.current?.()
unobserve.current = undefined
return unobserve
}
} else {
if (!visible) {
Expand Down

0 comments on commit bf82a47

Please sign in to comment.