Skip to content

useInViewport()

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

Defined in: src/hooks/dom/useInViewport.ts:44

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".

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.