Unverified Commit bf82a473 authored by Sukka's avatar Sukka Committed by GitHub

refactor(use-intersection): remove useRef usage (#39791)

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`.
parent 05b621aa
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import {
requestIdleCallback,
cancelIdleCallback,
......@@ -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) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment