feat: never render off screen

This commit is contained in:
TrèsAbhi committed 2024-08-26 21:47:14 -05:00
1 parent f58b6dcd17
commit 21ece80187
2 files changed
+31 -1

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
import { RefObject, useEffect, useRef, useState } from 'react';
/**
* Thanks GuCier!
*
* https://stackoverflow.com/a/65008608/12294756
*/
export default function useOnScreen(ref: RefObject<HTMLElement>) {
const [isIntersecting, setIntersecting] = useState(false);
const observer = useRef<IntersectionObserver>();
useEffect(() => {
observer.current = new IntersectionObserver(([entry]) =>
setIntersecting(entry.isIntersecting),
);
}, [ref]);
useEffect(() => {
if (!ref.current) return;
observer.current?.observe(ref.current);
return () => observer.current?.disconnect();
}, [ref]);
return isIntersecting;
}