DEV Community

Cover image for Boosting React App with Custom Hook : useOnScreen
Nicolas B.
Nicolas B.

Posted on • Updated on

Boosting React App with Custom Hook : useOnScreen

When it comes to building web applications, performance is a critical factor in ensuring a smooth user experience. One common requirement is to determine whether an element is currently visible on the screen. This task is essential for implementing features like lazy loading images, infinite scrolling, or tracking visibility-based events. In this article, we'll introduce you to a custom React hook called useOnScreen, which simplifies visibility detection in React applications, making your life as a developer easier.


Introducing useOnScreen

The useOnScreen hook is designed to help you detect whether an element is currently visible on the screen or not. It leverages the Intersection Observer API, a modern JavaScript feature that allows you to monitor changes in the visibility of elements. With this hook, you can easily determine whether an element is within the viewport, enabling you to trigger actions accordingly.

Here's how the useOnScreen hook works:

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

export const useOnScreen = (ref: RefObject<any>) => {
  const [isIntersecting, setIntersecting] = useState(false)
  const observer = new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting))

  useEffect(() => {
    observer.observe(ref.current)
    return () => {
      observer.unobserve(ref.current)
    }
  }, [])

  return isIntersecting
}
Enter fullscreen mode Exit fullscreen mode

How to Use useOnScreen

Here's a complete example of using the useOnScreen hook to progressively load an image when the user scrolls down the page and the image becomes visible:

import React, { useRef } from 'react'
import { useOnScreen } from './useOnScreen'

function App() {
  const imageRef = useRef()
  const isImageVisible = useOnScreen(imageRef)

  return (
    <div>
      <div style={{ height: '100vh' }}>Scroll down</div>
      <div ref={imageRef}>
        {isImageVisible && (
          <img src="image.jpg" alt="Image" />
        )}
      </div>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
codemaoz profile image
Manuel

Nice hook, thank you !