Skip to content

Commit

Permalink
Fix use-in-viewport when ref changes
Browse files Browse the repository at this point in the history
  • Loading branch information
fellmann authored Oct 1, 2024
1 parent 397e782 commit 10de94f
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions packages/@mantine/hooks/src/use-in-viewport/use-in-viewport.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useRef, useState } from "react";

export function useInViewport<T extends HTMLElement = any>() {
const ref = useRef<T>(null);
export function useInViewport<T extends HTMLElement>() {
const observer = useRef<IntersectionObserver | null>(null);
const [inViewport, setInViewport] = useState(false);

const observer = useMemo(() => {
if (typeof IntersectionObserver === 'undefined') {
return null;
const ref = useCallback((node: T | null) => {
if (typeof IntersectionObserver !== "undefined") {
if (node && !observer.current) {
observer.current = new IntersectionObserver(([entry]) =>
setInViewport(entry.isIntersecting)
);
} else {
observer.current?.disconnect();
}

if (node) {
observer.current?.observe(node);
} else {
setInViewport(false);
}
}
return new IntersectionObserver(([entry]) => setInViewport(entry.isIntersecting));
}, [ref]);

useEffect(() => {
if (ref.current && observer) {
observer.observe(ref.current);
return () => observer.disconnect();
}
return () => null;
}, []);

return { ref, inViewport };
Expand Down

0 comments on commit 10de94f

Please sign in to comment.