Skip to content

Instantly share code, notes, and snippets.

@tinykite
Last active October 29, 2019 00:18
Show Gist options
  • Save tinykite/afc66bb6d1ae969c8975f7c4e541d4e8 to your computer and use it in GitHub Desktop.
Save tinykite/afc66bb6d1ae969c8975f7c4e541d4e8 to your computer and use it in GitHub Desktop.
Intersection Observer Hooks Example
// 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