useOnScreen.js


Overview

useOnScreen.js defines a custom React Hook named useOnScreen that detects whether a referenced DOM element is currently visible within the viewport. It leverages the browser's native IntersectionObserver API to efficiently observe the visibility state of an element without polling or expensive event listeners.

This hook is primarily used to trigger UI changes or lazy-load content when an element scrolls into or out of view, improving performance and user experience in React applications.


Detailed Explanation

useOnScreen(ref)

Description

A React Hook that returns a boolean indicating whether the DOM element referenced by ref is visible on the user's screen.

Parameters

Returns

Usage Example

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

function LazyImage() {
  const imgRef = useRef();
  const isVisible = useOnScreen(imgRef);

  return (
    <img
      ref={imgRef}
      src={isVisible ? 'high-res-image.jpg' : 'placeholder.jpg'}
      alt="Lazy loaded example"
      style={{ width: '100%', height: 'auto' }}
    />
  );
}

In this example, the image source switches to a high-resolution image only when the image enters the viewport.


Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
  A[Component with ref] --> B[useOnScreen(ref)]
  B --> C[useState(isIntersecting)]
  B --> D[useEffect()]
  D --> E[IntersectionObserver]
  E --> F[observe ref.current]
  E --> G[callback: setIntersecting(entry.isIntersecting)]
  D --> H[cleanup: observer.disconnect()]
  B --> I[return isIntersecting]

Diagram Explanation:


Summary

useOnScreen.js is a lightweight, reusable React Hook that abstracts the complexity of the IntersectionObserver API to provide a simple boolean flag indicating element visibility on screen. It is useful in performance-sensitive React applications for implementing lazy loading and viewport-aware behaviors. The hook cleanly manages lifecycle and state with React hooks and requires only a single ref parameter to function.


End of Documentation