The `react-intersection-observer-hook` package provides declarative React hooks, specifically `useIntersectionObserver` and `useTrackVisibility`, to interact with the browser's native Intersection Observer API. It simplifies detecting when a React component enters or exits the viewport, enabling features like lazy loading, infinite scrolling, and triggering animations. The current stable version is 4.0.2, with active development focusing on modern React compatibility, demonstrated by its recent update for React 19 in v4.0.0. Releases are frequent, addressing bugs and improving API ergonomics. Key differentiators include a dedicated `useTrackVisibility` for simpler boolean visibility checks, explicit `rootRef` handling for scrollable containers, and robust support for both ES Modules and CommonJS environments since v3.0.0, ensured through modern bundling practices.
npm install react-intersection-observer-hookVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use `useTrackVisibility` to detect when a component enters or leaves the viewport, changing its background color. It also shows how to specify a custom scrollable container using `rootRef`.
Upgrade your project's React and React-DOM peer dependencies to v19 or higher, or explicitly install `react-intersection-observer-hook@^3` if you need to remain on an older React version.
Ensure your bundler (e.g., Webpack, Rollup, Vite) is configured to handle modern ES Modules and CommonJS interoperability correctly. Check `publint` and `Are the Types Wrong` documentation if module resolution issues persist.
If tracking multiple elements, use separate `useIntersectionObserver` instances for each, or manage multiple refs manually with a single observer if advanced control is needed.
Use the `rootRef` callback from the hook: `<ScrollableContainer ref={rootRef}><SomeComponent ref={ref}/></ScrollableContainer>`.Unless targeting extremely old browsers, avoid including `IntersectionObserver` polyfills to reduce bundle size and potential conflicts.
Always guard access to `entry` properties, e.g., `const isVisible = entry && entry.isIntersecting;`.
Ensure the hook is called within a React function component or another custom hook, and verify `react` and `react-dom` peer dependencies match your project's React version (especially for v4 requiring React 19).
Check your `tsconfig.json` (`moduleResolution`, `module`), `package.json` (`type`), and bundler configuration. Ensure you're using a modern bundler setup that supports `exports` field in `package.json`.