Skip to content

Instantly share code, notes, and snippets.

@marekpiechut
Created July 3, 2020 11:59
Show Gist options
  • Save marekpiechut/8ec02a64a150d6f5804d46f5ae648d88 to your computer and use it in GitHub Desktop.
Save marekpiechut/8ec02a64a150d6f5804d46f5ae648d88 to your computer and use it in GitHub Desktop.
Get lazy loading cheap with IntersectionObserver in React
const useLazyMediaLoad = media => {
const [url, setUrl] = useState<?string>(null)
const targetRef = useRef<?HTMLElement>(null)
useEffect(() => {
if (!IntersectionObserver) {
thumbLoader(media).then(setUrl)
} else if (targetRef.current) {
let observer = new IntersectionObserver(
entries =>
entries.forEach(entry => {
if (entry.isIntersecting) {
thumbLoader(media).then(setUrl)
observer = observer.disconnect()
}
}),
{ rootMargin: '0px 0px 200px 0px' }
)
observer.observe(targetRef.current)
return () => (observer = observer && observer.disconnect())
}
}, [media])
return [url, targetRef]
}
const ExerciseItem = ({ exercise }: Props) => {
const [url, targetRef] = useLazyMediaLoad(exercise.media)
return (
<div
css={styles.thumb}
style={{ backgroundImage: url ? `url(${url})` : MISSING_VIDEO }}
ref={targetRef}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment