Skip to content

Instantly share code, notes, and snippets.

@jhammann
Last active November 8, 2024 10:10
Show Gist options
  • Select an option

  • Save jhammann/404f2575704fe1ab612790a3ef28389c to your computer and use it in GitHub Desktop.

Select an option

Save jhammann/404f2575704fe1ab612790a3ef28389c to your computer and use it in GitHub Desktop.
A React hook to check if something has been seen in the viewport
export function Component() {
const { ref } = useWhenViewed({
onInView: () => {
// do cool things here
},
});
return (
<div ref={ref}>Your content here</div>
);
}
import { useEffect, useState } from "react";
import { useInView } from "react-intersection-observer";
interface UseWhenViewed {
onInView: () => void;
threshold?: number;
}
export function useWhenViewed({ onInView, threshold = 0.25 }: UseWhenViewed) {
const hasBeenInView = useRef(false);
const { ref, inView } = useInView({ threshold });
useEffect(() => {
if (inView && !hasBeenInView.current) {
hasBeenInView.current = true;
onInView();
}
}, [inView, hasBeenInView, onInView]);
return { ref };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment