Last active
November 8, 2024 10:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function Component() { | |
| const { ref } = useWhenViewed({ | |
| onInView: () => { | |
| // do cool things here | |
| }, | |
| }); | |
| return ( | |
| <div ref={ref}>Your content here</div> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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