Skip to content

Instantly share code, notes, and snippets.

@yongdamsh
Last active August 30, 2020 13:33
Show Gist options
  • Save yongdamsh/aa03ef7f5875e7c9c334c3fff0c8f656 to your computer and use it in GitHub Desktop.
Save yongdamsh/aa03ef7f5875e7c9c334c3fff0c8f656 to your computer and use it in GitHub Desktop.
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
// Custom hook
function useLazyImageObserver(target) {
useEffect(() => {
if (!target.current) {
return;
}
let observer = new window.IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
observer.unobserve(lazyImage);
}
});
});
observer.observe(target.current);
return () => {
if (observer) {
observer.disconnect();
observer = null;
}
};
}, [target]);
}
// Component
function App() {
const target = useRef(null);
useLazyImageObserver(target);
return (
<section>
<div style={{ height: "2000px" }} />
<img ref={target} data-src="https://placeimg.com/320/100/any" alt="" />
</section>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment