Skip to content

Commit 4893856

Browse files
committed
Create useOnScreen hooks
Hook which returns boolean representing is element is visible on screen
1 parent 3eb3b85 commit 4893856

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/hooks/useOnScreen.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { useEffect, useState } from "react";
2+
3+
function useOnScreen(ref, rootMargin = "0px") {
4+
// State and setter for storing whether element is visible
5+
const [isIntersecting, setIntersecting] = useState(false);
6+
7+
useEffect(() => {
8+
const observer = new IntersectionObserver(
9+
([entry]) => {
10+
// Update our state when observer callback fires
11+
setIntersecting(entry.isIntersecting);
12+
},
13+
{
14+
rootMargin,
15+
}
16+
);
17+
if (ref.current) {
18+
observer.observe(ref.current);
19+
}
20+
return () => {
21+
observer.disconnect();
22+
};
23+
});
24+
25+
return isIntersecting;
26+
}
27+
28+
export default useOnScreen;

0 commit comments

Comments
 (0)