Last active
October 29, 2019 00:18
-
-
Save tinykite/afc66bb6d1ae969c8975f7c4e541d4e8 to your computer and use it in GitHub Desktop.
Intersection Observer Hooks Example
This file contains 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 React and React Hooks for Triggering Animation | |
import React, { useState, useEffect, useRef } from 'react'; | |
// From the Use Hooks Website | |
// https://usehooks.com/useOnScreen | |
// Also available as a Node Module | |
// https://github.com/thebuilder/react-intersection-observer | |
function useOnScreen(ref) { | |
// State and setter for storing whether element is visible | |
const [isIntersecting, setIntersecting] = useState(false); | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
// Update our state when observer callback fires | |
setIntersecting(entry.isIntersecting); | |
console.log("Look, I'm being observed!"); | |
}, | |
{ | |
threshold: [0] | |
} | |
); | |
if (ref.current) { | |
observer.observe(ref.current); | |
} | |
return () => { | |
observer.unobserve(ref.current); | |
}; | |
}, []); // This empty array makes sure the effect is only run on mount and unmount | |
return isIntersecting; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment