Skip to content

Instantly share code, notes, and snippets.

@LishuGupta652
Created June 13, 2020 07:48
Show Gist options
  • Save LishuGupta652/b2a3ebd41b3ce32a6ae4a952e050b9d3 to your computer and use it in GitHub Desktop.
Save LishuGupta652/b2a3ebd41b3ce32a6ae4a952e050b9d3 to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from "react";
import { useIntersection } from "react-use";
export const IntersectionContext = React.createContext({ inView: true });
export const IntersectionObserver = ({
children,
reset = false // if value set to true - observed element will reappear every time it shows up on the screen
}) => {
const [inView, setInView] = useState(false);
const intersectionRef = React.useRef(null);
const intersection = useIntersection(intersectionRef, {
threshold: 0
});
useEffect(() => {
const inViewNow = intersection && intersection.intersectionRatio > 0;
if (inViewNow) {
return setInView(inViewNow);
} else if (reset) {
return setInView(false);
}
}, [intersection, reset]);
return (
<IntersectionContext.Provider value={{ inView }}>
<div ref={intersectionRef}>{children}</div>
</IntersectionContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment