Skip to content

useInViewport()

useInViewport(reference, offset?, debounce?): boolean

Defined in: hooks/dom/useInViewport.ts:79

A custom React hook to check if a DOM element is within the viewport. Allows specifying an offset to consider elements near the edge of the viewport as "visible".

The initial visibility is computed synchronously on mount based on the current reference.current value, and then kept up to date on scroll and resize events.

Parameters

reference

RefObject<HTMLElement>

A React ref object pointing to the target element.

offset?

number = 0

Offset in pixels to extend the viewport boundary.

debounce?

number = 100

The debounce delay in milliseconds for scroll and resize events.

Returns

boolean

isVisible - Whether the element is within the viewport (considering offset).

Example

tsx
import { useRef } from 'react';
import { useInViewport } from '@zl-asica/react';

const MyComponent = () => {
  const ref = useRef<HTMLDivElement>(null);
  const isVisible = useInViewport(ref, 50); // 50px offset

  return (
    <div>
      <div style={{ height: '150vh', background: 'lightgray' }}>Scroll down</div>
      <div
        ref={ref}
        style={{
          height: '100px',
          backgroundColor: isVisible ? 'green' : 'red',
        }}
      >
        {isVisible ? 'Visible' : 'Not Visible'}
      </div>
      <div style={{ height: '150vh', background: 'lightgray' }} />
    </div>
  );
};

Released under the MIT License.