react-intersection-observer-hook
This is a simple to use React hook package for using Insersection Observer declaratively. By using this hook, you can easily track if a component is visible or not, create lazy loading images, trigger animations on entering or leaving the viewport, implement infinite loading etc.
Live demo is here.
This package relies on Intersection Observer API. Browser compatibility can be seen in here.
If you want to support the browsers those are not supporting it natively, you can use a polyfill.
Installation
npm install react-intersection-observer-hook
Usage
import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
function Example() {
const [ref, { entry }] = useIntersectionObserver();
const isVisible = entry && entry.isIntersecting;
useEffect(() => {
console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
}, [isVisible]);
return <SomeComponentToTrack ref={ref} />;
}
If you have a scrollable container, you can set a root
like this:
import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
function Example() {
const [ref, { entry, rootRef }] = useIntersectionObserver();
const isVisible = entry && entry.isIntersecting;
useEffect(() => {
console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
}, [isVisible]);
return (
<ScrollableContainer
// We use `rootRef` callback to set the root node.
ref={rootRef}
>
<SomeComponentToTrack ref={ref} />
</ScrollableContainer>
);
}
If you just want to track visibility, you can also use useTrackVisibility
hook.
It has the same API as useIntersectionObserver
hook. It just returns additional fields as its second tuple item.
import React, { useEffect } from 'react';
import { useTrackVisibility } from 'react-intersection-observer-hook';
function Example() {
const [ref, { entry, rootRef, isVisible, wasEverVisible }] =
useTrackVisibility();
useEffect(() => {
console.log(`The component is ${isVisible ? 'visible' : 'not visible'}.`);
}, [isVisible]);
return <SomeComponentToTrack ref={ref} />;
}
You can find more usage examples in the demo
app in this repository.
Arguments
Both useIntersectionObserver
and useTrackVisibility
gets the same arguments. And those are;
- rootMargin: Indicates the margin value around the root element. Default value is zero for all directions (top, right, bottom and left).
- threshold: Threshold value (or values) to trigger the observer.
For more info, you can check here and here.
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!