Created
August 2, 2022 12:05
-
-
Save isNan909/27a29be3a858033284658faab435e0f9 to your computer and use it in GitHub Desktop.
Lazy load images in React
This file contains hidden or 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 LazyLoadImage = ({ | |
| alt, | |
| src, | |
| className, | |
| loadInitially = false, | |
| observerOptions = { root: null, rootMargin: '200px 0px' }, | |
| ...props | |
| }) => { | |
| const observerRef = React.useRef(null); | |
| const imgRef = React.useRef(null); | |
| const [isLoaded, setIsLoaded] = React.useState(loadInitially); | |
| const observerCallback = React.useCallback( | |
| entries => { | |
| if (entries[0].isIntersecting) { | |
| observerRef.current.disconnect(); | |
| setIsLoaded(true); | |
| } | |
| }, | |
| [observerRef] | |
| ); | |
| React.useEffect(() => { | |
| if (loadInitially) return; | |
| if ('loading' in HTMLImageElement.prototype) { | |
| setIsLoaded(true); | |
| return; | |
| } | |
| observerRef.current = new IntersectionObserver( | |
| observerCallback, | |
| observerOptions | |
| ); | |
| observerRef.current.observe(imgRef.current); | |
| return () => { | |
| observerRef.current.disconnect(); | |
| }; | |
| }, []); | |
| return ( | |
| <img | |
| alt={alt} | |
| src={isLoaded ? src : ''} | |
| ref={imgRef} | |
| className={className} | |
| loading={loadInitially ? undefined : 'lazy'} | |
| {...props} | |
| /> | |
| ); | |
| }; | |
| //usage | |
| ReactDOM.render( | |
| <LazyLoadImage | |
| src="https://picsum.photos/id/1080/600/600" | |
| alt="Strawberries" | |
| />, | |
| document.getElementById('root') | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment