react-in-viewport, react-intersection-observer, and react-visibility-sensor are all React libraries designed to detect when an element enters or leaves the browser's visible area. They solve common problems like lazy loading images, triggering animations, or tracking user engagement. While they share a similar goal, they differ significantly in their underlying implementation, API design, and maintenance status. react-intersection-observer is the modern standard, leveraging the native Intersection Observer API for high performance. react-in-viewport offers a lightweight wrapper with a focus on simplicity. react-visibility-sensor is a legacy solution that relies on older scroll/resize event listeners, making it less efficient for modern applications.
react-intersection-observer vs react-in-viewport vs react-visibility-sensorDetecting when an element appears on screen is a common requirement for lazy loading images, triggering animations, or analyzing user behavior. While react-in-viewport, react-intersection-observer, and react-visibility-sensor all aim to solve this, their approaches vary wildly in terms of performance, API design, and long-term viability. Let's break down how they work and which one fits your architecture.
The most critical difference lies in how these libraries detect visibility.
react-intersection-observer uses the browser's native Intersection Observer API. This is a highly optimized, asynchronous browser feature that notifies you only when visibility changes, without blocking the main thread.
// react-intersection-observer: Uses native Intersection Observer
import { useInView } from 'react-intersection-observer';
function MyComponent() {
const { ref, inView } = useInView({
threshold: 0.5,
});
return (
<div ref={ref}>
{inView ? 'Visible' : 'Hidden'}
</div>
);
}
react-in-viewport also wraps the Intersection Observer API but exposes it primarily through a Render Prop or Higher-Order Component (HOC) pattern. It abstracts the observer setup but still relies on the efficient native browser implementation.
// react-in-viewport: Wrapper around Intersection Observer
import InViewport from 'react-in-viewport';
function MyComponent() {
return (
<InViewport>
{({ inViewport }) => (
<div>
{inViewport ? 'Visible' : 'Hidden'}
</div>
)}
</InViewport>
);
}
react-visibility-sensor relies on scroll and resize event listeners. It calculates element position manually on every event fire. This forces the browser to recalculate layout constantly, which can cause stuttering and high CPU usage, especially on mobile devices.
// react-visibility-sensor: Uses scroll/resize listeners (Legacy)
import VisibilitySensor from 'react-visibility-sensor';
function MyComponent() {
const onChange = (isVisible) => {
console.log(isVisible ? 'Visible' : 'Hidden');
};
return (
<VisibilitySensor onChange={onChange}>
<div>Check Visibility</div>
</VisibilitySensor>
);
}
Modern React development favors hooks for stateful logic, but older libraries often use Render Props or HOCs.
react-intersection-observer offers a clean Hook-based API (useInView), making it easy to compose logic inside functional components without nesting wrappers. It also supports a Component API if needed.
// react-intersection-observer: Hook API
const { ref, entry } = useInView({ trackVisibility: true });
// Access detailed entry data
console.log(entry.intersectionRatio);
react-in-viewport uses a Render Prop pattern. You pass a function as a child to receive the visibility state. This can lead to "wrapper hell" if you need to track multiple elements deeply nested in your tree.
// react-in-viewport: Render Prop API
<InViewport>
{({ inViewport, ref }) => (
<div ref={ref}>
{inViewport && <LazyImage />}
</div>
)}
</InViewport>
react-visibility-sensor uses a Component-based API with callbacks. It requires you to manage state in the parent component and pass it down via the onChange prop. This pattern is verbose and feels dated in modern React.
// react-visibility-sensor: Callback API
class Parent extends React.Component {
state = { visible: false };
render() {
return (
<VisibilitySensor onChange={(v) => this.setState({ visible: v })}>
<div>{this.state.visible ? 'Seen' : 'Not Seen'}</div>
</VisibilitySensor>
);
}
}
Performance is where the choice becomes obvious for high-traffic sites.
react-intersection-observer allows fine-grained control over thresholds and root margins. You can trigger callbacks when 10%, 50%, or 100% of the element is visible, or even when it crosses a specific container boundary.
// react-intersection-observer: Advanced configuration
const { ref } = useInView({
threshold: [0, 0.5, 1], // Trigger at 0%, 50%, and 100%
rootMargin: '0px 0px -100px 0px', // Trigger 100px before element ends
});
react-in-viewport supports similar configuration options like threshold and delayTime, but the API is slightly less flexible regarding multiple thresholds compared to the direct hook exposure in react-intersection-observer.
// react-in-viewport: Configuration via props
<InViewport threshold={0.5} delayTime={100}>
{({ inViewport }) => <div>{inViewport ? 'Loaded' : ''}</div>}
</InViewport>
react-visibility-sensor has configuration for partialVisibility and offset, but because it runs calculations on every scroll event, adding complex offsets or checking partial visibility frequently degrades performance rapidly.
// react-visibility-sensor: Basic offset config
<VisibilitySensor offset={{ top: 100 }} partialVisibility>
<div>Sensor</div>
</VisibilitySensor>
When choosing a library, you must consider its lifespan.
react-intersection-observer is the industry standard. It is widely adopted, actively maintained, and regularly updated to match new browser specs. It is the safest bet for long-term projects.
react-in-viewport is a viable alternative but has a smaller community. It works well for simple use cases but may lag behind in adopting new Intersection Observer features or React patterns.
react-visibility-sensor is deprecated. The repository indicates it is no longer actively developed, and the maintainers explicitly recommend switching to Intersection Observer-based solutions. Using this in new projects introduces technical debt and performance risks immediately.
| Feature | react-intersection-observer | react-in-viewport | react-visibility-sensor |
|---|---|---|---|
| Core Tech | Native Intersection Observer | Native Intersection Observer | Scroll/Resize Listeners |
| Performance | ⭐⭐⭐⭐⭐ (Excellent) | ⭐⭐⭐⭐ (Very Good) | ⭐ (Poor) |
| API Style | Hooks & Components | Render Props / HOC | Class/Callback Components |
| Maintenance | ✅ Active | ⚠️ Moderate | ❌ Deprecated |
| Best For | Modern Apps, Complex Logic | Simple Wrappers | Legacy Maintenance Only |
For any new development, react-intersection-observer is the clear winner. Its hook-based API fits naturally into modern React, and its reliance on the native Intersection Observer API ensures your app remains fast and responsive. It handles edge cases, multiple thresholds, and performance constraints better than any alternative.
Use react-in-viewport only if you are stuck in a codebase that heavily relies on Render Props and you need a quick, compatible swap for basic visibility checks without refactoring to hooks.
Avoid react-visibility-sensor entirely. Its reliance on scroll events is an anti-pattern in modern web development. If you encounter it in an existing project, plan to refactor it out as soon as possible to improve user experience and reduce main-thread blocking.
Choose react-in-viewport if you need a very simple, drop-in component wrapper for basic 'in-view' checks and prefer a render-prop or HOC pattern over hooks. It is lighter in terms of API surface area but may lack the granular control and extensive feature set of react-intersection-observer. Ensure you verify its current maintenance status before adopting, as it is less widely adopted than the observer-based solution.
Choose react-intersection-observer for almost all new projects. It is the most robust, performant, and actively maintained option. It provides full access to the native Intersection Observer API, supporting advanced features like multiple root margins, thresholds, and tracking visibility changes without causing layout thrashing. Its hook-based API (useInView) integrates seamlessly with modern React functional components.
Do NOT choose react-visibility-sensor for new projects. This library is effectively deprecated and relies on inefficient scroll and resize event listeners rather than the native Intersection Observer API. This approach causes significant performance issues, especially on mobile devices or pages with frequent scrolling, leading to janky user experiences. You should only consider this if you are maintaining a legacy codebase that cannot be refactored immediately.
Library to detect whether or not a component is in the viewport, using the Intersection Observer API.
This library also uses MutationObserver to detect the change of the target element.
npm install --save react-in-viewport
yarn add react-in-viewport
A common use case is to load an image when a component is in the viewport (lazy load).
We have traditionally needed to monitor scroll position and calculate the viewport size, which can be a scroll performance bottleneck.
Modern browsers now provide a new API--Intersection Observer API--which can make implementating this effort much easier and performant.
For browsers not supporting the API, you will need to load a polyfill. Browser support table
require('intersection-observer');
The core logic is written using React Hooks. We provide two interfaces: you can use handleViewport, a higher order component (HOC) for class based components, or use hooks directly, for functional components.
The HOC acts as a wrapper and attaches the intersection observer to your target component. The HOC will then pass down extra props, indicating viewport information and executing a callback function when the component enters and leaves the viewport.
When wrapping your component with handleViewport HOC, you will receive inViewport props indicating whether the component is in the viewport or not.
handleViewport HOC accepts three params: handleViewport(Component, Options, Config)
| Params | Type | Description |
|---|---|---|
| Component | React Element | Callback function for when the component enters the viewport |
| Options | Object | Options you want to pass to Intersection Observer API |
| Config | Object | Configs for HOC (see below) |
| Params | Type | Default | Description |
|---|---|---|---|
| disconnectOnLeave | boolean | false | Disconnect intersection observer after leave |
| Props | Type | Default | Description |
|---|---|---|---|
| onEnterViewport | function | Callback function for when the component enters the viewport | |
| onLeaveViewport | function | Callback function for when the component leaves the viewport |
The HOC preserves onEnterViewport and onLeaveViewport props as a callback
| Props | Type | Default | Description |
|---|---|---|---|
| inViewport | boolean | false | Whether your component is in the viewport |
| forwardedRef | React ref | Assign this prop as a ref on your component | |
| enterCount | number | Numbers of times your component has entered the viewport | |
| leaveCount | number | Number of times your component has left the viewport |
NOTE: Need to add ref={this.props.forwardedRef} to your component
import handleViewport, { type InjectedViewportProps } from 'react-in-viewport';
const Block = (props: InjectedViewportProps<HTMLDivElement>) => {
const { inViewport, forwardedRef } = props;
const color = inViewport ? '#217ac0' : '#ff9800';
const text = inViewport ? 'In viewport' : 'Not in viewport';
return (
<div className="viewport-block" ref={forwardedRef}>
<h3>{ text }</h3>
<div style={{ width: '400px', height: '300px', background: color }} />
</div>
);
};
const ViewportBlock = handleViewport(Block, /** options: {}, config: {} **/);
const Component = (props) => (
<div>
<div style={{ height: '100vh' }}>
<h2>Scroll down to make component in viewport</h2>
</div>
<ViewportBlock onEnterViewport={() => console.log('enter')} onLeaveViewport={() => console.log('leave')} />
</div>
))
enterCount.leaveCount.import React, { Component } from 'react';
import handleViewport from 'react-in-viewport';
class MySectionBlock extends Component {
getStyle() {
const { inViewport, enterCount } = this.props;
//Fade in only the first time we enter the viewport
if (inViewport && enterCount === 1) {
return { WebkitTransition: 'opacity 0.75s ease-in-out' };
} else if (!inViewport && enterCount < 1) {
return { WebkitTransition: 'none', opacity: '0' };
} else {
return {};
}
}
render() {
const { enterCount, leaveCount, forwardedRef } = this.props;
return (
<section ref={forwardedRef}>
<div className="content" style={this.getStyle()}>
<h1>Hello</h1>
<p>{`Enter viewport: ${enterCount} times`}</p>
<p>{`Leave viewport: ${leaveCount} times`}</p>
</div>
</section>
);
}
}
const MySection = handleViewport(MySectionBlock, { rootMargin: '-1.0px' });
export default MySection;
Alternatively, you can also directly using useInViewport hook which takes similar configuration as HOC.
import React, { useRef } from 'react';
import { useInViewport } from 'react-in-viewport';
const MySectionBlock = () => {
const myRef = useRef(null);
const {
inViewport,
enterCount,
leaveCount,
} = useInViewport(
myRef,
options,
config = { disconnectOnLeave: false },
props
);
return (
<section ref={myRef}>
<div className="content" style={this.getStyle()}>
<h1>Hello</h1>
<p>{`Enter viewport: ${enterCount} times`}</p>
<p>{`Leave viewport: ${leaveCount} times`}</p>
</div>
</section>
);
};