react-inview – A lightweight React hook to detect when elements enter or leave the viewport using the Intersection Observer API.
npm install @ehsaneha/react-inviewonce flag to trigger visibility callback only once
disabled prop to toggle observation on and off dynamically
bash
npm install @ehsaneha/react-inview
`
or
`bash
yarn add @ehsaneha/react-inview
`
Usage
$3
`tsx
import React from "react";
import useInView from "@ehsaneha/react-inview";
function Example() {
const [ref, isVisible] = useInView({ threshold: 0.5 });
return (
{isVisible ? "Visible" : "Not visible"}
);
}
`
API
$3
- props (optional): Configuration options
- rootMargin (string): Margin around the root. Default "0px"
- threshold (number | number\[]): Threshold(s) at which to trigger. Default 0
- once (boolean): Whether to disconnect observer after first visibility. Default false
- disabled (boolean): Whether to disable the observer. Default false
Returns a tuple with:
- ref: React ref to assign to the element to observe
- isVisible: Boolean indicating whether the element is currently visible
---
$3
Stateless version that accepts a callback instead of returning state.
---
Testing
Tests are written using Jest and React Testing Library Hooks.
`bash
npm test
`
Mocks the Intersection Observer API to verify:
- Observation starts and stops correctly
- disabled toggling works dynamically
- once` flag disconnects observer after first visibility event