Skip to content

Instantly share code, notes, and snippets.

@marekpiechut
Created July 3, 2020 11:59
Show Gist options
  • Select an option

  • Save marekpiechut/aceb875475ffbbb32bbb0dc164dea5d6 to your computer and use it in GitHub Desktop.

Select an option

Save marekpiechut/aceb875475ffbbb32bbb0dc164dea5d6 to your computer and use it in GitHub Desktop.
Get lazy loading cheap with IntersectionObserver in React
const ExerciseItem = ({ exercise, thumbLoader }: Props) => {
const [url, setUrl] = useState<?string>(null)
const thisRef = useRef<?HTMLDivElement>(null)
const media = exercise.media.id
useEffect(() => {
if (IntersectionObserver) {
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(thisRef.current)
return () => (observer = observer && observer.disconnect())
} else {
thumbLoader(media).then(setUrl)
}
}, [media, thumbLoader])
return (
<div
css={styles.thumb}
style={{ backgroundImage: `url(${url})` }}
ref={thisRef}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment