DEV Community

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

Posted on • Edited on

4

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (1)

Collapse
 
codemaoz profile image
Manuel

Nice hook, thank you !

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay