Created
July 3, 2020 11:59
-
-
Save marekpiechut/8ec02a64a150d6f5804d46f5ae648d88 to your computer and use it in GitHub Desktop.
Get lazy loading cheap with IntersectionObserver in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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