useOnScreen

Here's an example of a custom hook that uses the IntersectionObserver API to detect whether an element is currently visible on the screen:

import { useState, useEffect, useRef } from 'react'

function useOnScreen(ref) {
  const [isIntersecting, setIsIntersecting] = useState(false)

  const observer = useRef(
    new IntersectionObserver(([entry]) => {
      setIsIntersecting(entry.isIntersecting)
    })
  )

  useEffect(() => {
    observer.current.disconnect()

    if (ref.current) {
      observer.current.observe(ref.current)
    }

    return () => {
      observer.current.disconnect()
    }
  }, [ref])

  return isIntersecting
}

This custom hook takes a ref as a parameter and returns a boolean indicating whether that element is currently visible on the screen. We use the useState Hook to keep track of whether the element is intersecting the viewport, and a useRef Hook to store an instance of the IntersectionObserver class. We then use the useEffect Hook to observe the target element for intersection changes, and disconnect the observer when the component unmounts.

To use this custom hook, you would call it in your functional component and pass a ref to the element you want to observe:

function MyComponent() {
  const ref = useRef(null)
  const isOnScreen = useOnScreen(ref)

  return (
    <div>
      <h1 ref={ref}>Hello, world!</h1>
      {isOnScreen && <p>The element is currently visible on the screen.</p>}
    </div>
  )
}

In this example, we create a ref using the useRef Hook and attach it to the h1 element. We then call the useOnScreen hook with the ref and use the boolean return value to conditionally render a message indicating whether the element is currently visible on the screen. By using the useOnScreen Hook, we can easily detect when an element is visible on the screen and trigger actions accordingly.

Codesandbox Example