Skip to content

Instantly share code, notes, and snippets.

@nirajrajgor
Created July 19, 2020 15:14
Show Gist options
  • Save nirajrajgor/f00a7a05d662c89feb666023a62678f0 to your computer and use it in GitHub Desktop.
Save nirajrajgor/f00a7a05d662c89feb666023a62678f0 to your computer and use it in GitHub Desktop.
Progressive load image component in react with hooks
import React, { useState, useEffect } from 'react';
const ImageLoad = React.memo(({ src, placeholder, alt = "" }) => {
const [loading, setLoading] = useState(true);
const [currentSrc, updateSrc] = useState(placeholder);
useEffect(() => {
// start loading original image
const imageToLoad = new Image();
imageToLoad.src = src;
imageToLoad.onload = () => {
// When image is loaded replace the src and set loading to false
setLoading(false);
updateSrc(src);
}
}, [src])
return (
<img
src={currentSrc}
style={{
opacity: loading ? 0.5 : 1,
transition: "opacity .15s linear"
}}
alt={alt}
/>
)
});
export default ImageLoad;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment