Skip to content

Instantly share code, notes, and snippets.

@ShizukuIchi
Last active February 4, 2019 17:33
Show Gist options
  • Save ShizukuIchi/72463e47aa7a0c78416fa405fcbd15b9 to your computer and use it in GitHub Desktop.
Save ShizukuIchi/72463e47aa7a0c78416fa405fcbd15b9 to your computer and use it in GitHub Desktop.
React hook observes intersection of a node.
import { useState, useEffect } from 'react';
require('intersection-observer');
function useVisibility(ref , ratio = 0.1) {
const [visible, setVisible] = useState(false);
const callback = entries => {
entries.forEach(entry => {
setVisible(entry.intersectionRatio >= ratio)
})
}
useEffect(
() => {
const options = {
threshold: ratio,
};
const observer = new IntersectionObserver(callback, options);
const target = ref.current
if (!target) return;
observer.observe(target);
return () => {
observer.disconnect();
};
},
[ratio],
);
return visible;
}
export default useVisibility;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment