Rooks
HooksUI & Layout

useInViewRef

Returns a callback ref and whether its element currently intersects an observer root.

About

useInViewRef is the state-oriented Intersection Observer hook. Attach its callback ref to one element to receive a boolean, and optionally provide a raw observer callback for entry details.

Example

import { useMemo } from "react";
import { useInViewRef } from "rooks";

export default function VisibilityStatus() {
  const options = useMemo(() => ({ threshold: 0.5 }), []);
  const [targetRef, inView] = useInViewRef(options);

  return (
    <section>
      <p aria-live="polite">
        The panel is {inView ? "at least half visible" : "not half visible"}.
      </p>
      <div
        ref={targetRef}
        style={{ minHeight: 160, border: "1px solid", padding: 16 }}
      >
        Scroll this panel through the viewport.
      </div>
    </section>
  );
}

Parameters

The supported overloads are:

  • no arguments;
  • an IntersectionObserverInit object; or
  • an IntersectionObserverCallback followed by an optional options object.

With no arguments, the defaults are root: null, rootMargin: "0px 0px 0px 0px", and threshold: [0, 1]. A supplied options object is passed through rather than merged with that object; omitted fields then use the browser's defaults.

Return value

Returns [ref, inView]. ref is a stable callback ref for an HTMLElement. inView starts as false and becomes the latest observed entry's isIntersecting value.

Behavior and lifecycle

An observer is created after the ref receives a node. Each notification updates inView and then invokes the optional callback with the original entries and observer. The observer disconnects when the node, callback, or relevant options change and on unmount.

Memoize a custom options object and callback when their semantic values are stable. A new object or callback identity can disconnect and recreate the observer on every render.

The hook does not catch constructor errors from invalid roots, margins, or threshold values.

Compatibility and accessibility

Effects do not run during server rendering, so the server value is false. Attaching the ref in a browser without IntersectionObserver throws when the effect creates the observer; load a polyfill or provide a product-level fallback for such browsers.

Do not withhold essential or focusable content solely because inView is false: assistive technologies and search/indexing do not navigate like a visual viewport. Reserve lazy behavior for enhancements and preserve a usable no-observer experience. See SSR and browser APIs.

On this page