use-in-viewport-react

A lightweight and performant React hook to check if an element is in the viewport using the Intersection Observer API. This hook allows you to easily track an elementβs visibility and trigger UI updates, animations, lazy loading, or other effects when an element enters or leaves the viewport.
π Features
β
Tiny & Fast β Uses the native IntersectionObserver API for efficient performance.
β
Customizable β Supports root
, rootMargin
, and threshold
options for precise control.
β
Simple API β Just pass a ref
, and get a boolean
indicating visibility.
β
No Dependencies β Pure React, works with React 16.8+ (including React 19).
β
SSR Compatible β Works well with frameworks like Next.js.
Installation
To install the package, run:
npm install use-in-viewport-react
Usage
Example Usage in a Functional Component
import { useRef } from 'react';
import { useInViewportReact } from 'use-in-viewport-react';
function App() {
const ref = useRef<HTMLDivElement>(null);
const isInViewport = useInViewportReact(ref, {
threshold: 1,
});
return (
<div>
<h1>Testing useInViewportReact Hook</h1>
<div style={{ height: '100vh', background: '#f0f0f0' }}>
<p>
Scroll down to see the change in color when the box comes into view.
</p>
</div>
<div
ref={ref}
style={{
height: '200px',
background: isInViewport ? 'green' : 'red',
transition: 'background-color 0.3s ease',
}}
>
This element is {isInViewport ? 'in' : 'out of'} the viewport.
</div>
<div style={{ height: '100vh', background: '#f0f0f0' }}>
<p>Scroll further to test the visibility change.</p>
</div>
</div>
);
}
export default App;
π Use Cases
πΉ Lazy Load Images & Components β Load content only when it becomes visible to optimize performance.
πΉ Infinite Scrolling β Detect when users reach the bottom of a list and fetch more content dynamically.
πΉ Trigger Animations β Animate elements when they appear in the viewport for a better UX.
πΉ Sticky Elements β Change styles or behavior when an element enters/leaves the viewport.
πΉ Ad Tracking & Analytics β Track when specific content is visible to users.
βοΈ Options
Option | Type | Default | Description |
---|
root | Element | null | null | The element used as the viewport. Defaults to null (browser viewport). |
rootMargin | string | "0" | Margin around the root element (e.g., "10px" ). |
threshold | number | number[] | 0.1 | Visibility percentage that triggers the observer. |
π οΈ Compatibility
β
React 16.8+ (Hooks API)
β
React 17, 18, and 19
β
ES5 & ES6 compatible
β
Works with Next.js, Gatsby, Vite, and Create React App
π Why use use-in-viewport-react
?
There are several similar hooks available, but use-in-viewport-react
is optimized for performance, simplicity, and flexibility. It helps you build smooth scrolling experiences, lazy load content, and create engaging animations with minimal effort.