Skip to main content
Version: 5.6.1

useIntersectionObserverRef

About​

A hook to register an intersection observer listener.

Installation​

npm install --save rooks

Importing the hook​

import { useIntersectionObserverRef } from "rooks";

Usage​

function Demo() {
const [isVisible, setIsVisible] = useState(false);
const callback = (entries) => {
if (entries && entries[0]) {
setIsVisible(entries[0].isIntersecting);
}
};
const [myRef] = useIntersectionObserverRef(callback);
return (
<>
<div
style={{
position: "fixed",
top: 0,
right: 0,
}}
>
<h1>Is rectangle visible - {String(isVisible)}</h1>
</div>
<div style={{ height: 2000 }}></div>
<div ref={myRef} style={{ height: 300, background: "red" }}></div>
<div style={{ height: 2000 }}></div>
</>
);
return null;
}

render(<Demo />);

Arguments​

ArgumentTypeDescriptionDefault Value
callbackIntersectionObserverCallbackCallback that will be fired when the intersection occursundefined
optionsIntersectionObserverInitIntersection Observer config (read more){ root: null,rootMargin: "0px 0px 0px 0px", threshold: [0, 1]}

Return​

Returns an array with the first element in the array being the callback ref for the React component/element that needs to be observed.

Return valueTypeDescriptionDefault value
refCallbackRefref for the React component/element that needs to be observed.null

Codesandbox Example​

Basic usage​

Join Bhargav's discord server​

You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.