Last active
April 14, 2023 12:58
-
-
Save KobbyMmo/7be34195a713dc8a77a7bb2fc4d446ba to your computer and use it in GitHub Desktop.
Lazy Loading 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
import PropTypes from "prop-types"; | |
import React from "react"; | |
function Image({ src: ImageSrc, root, rootMargin, threshold, alt, ...props }) { | |
const [src, setSrc] = React.useState(false); | |
const imageRef = React.useRef(null); | |
const callback = React.useCallback((entries) => { | |
const [entry] = entries; | |
if (entry.isIntersecting) { | |
setSrc(ImageSrc); | |
} | |
}, []); | |
React.useEffect(() => { | |
const observer = new IntersectionObserver(callback, { | |
root, | |
rootMargin, | |
threshold, | |
}); | |
observer.observe(imageRef); | |
return () => { | |
observer.disconnect(); | |
}; | |
}, [callback, root, rootMargin, threshold, imageRef]); | |
return <img src={src} alt={alt} {...props} />; | |
} | |
Image.propTypes = { | |
alt: PropTypes.string.isRequired, | |
root: PropTypes.oneOfType([ | |
null, | |
PropTypes.func, | |
PropTypes.shape({ current: PropTypes.instanceOf(Element) }), | |
]), | |
rootMargin: PropTypes.string, | |
src: PropTypes.string.isRequired, | |
threshold: PropTypes.number, | |
}; | |
Image.defaultProps = { | |
root: null, | |
rootMargin: "0px", | |
threshold: 0.01, | |
}; |
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
import React, { Suspense } from "react"; | |
import About from './About' | |
const Posts = React.lazy(() => import("./Posts")); | |
const Newsletter = React.lazy(() => import("./Newsletter")); | |
function About() { | |
return ( | |
<div> | |
<About/> | |
<Suspense fallback={<div>Loading...</div>}> | |
<section> | |
<Posts /> | |
<Newsletter /> | |
</section> | |
</Suspense> | |
</div> | |
); | |
} |
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
import { FixedSizeList as List } from "react-window"; | |
function itemKey(index, data) { | |
const item = data[index]; | |
return item.id; | |
} | |
const Item = ({ index, style }) => <div style={style}>Item {index}</div>; | |
const Table = () => ( | |
<List | |
itemKey={itemKey} | |
height={150} | |
itemCount={1000} | |
itemSize={35} | |
width={300} | |
> | |
{Item} | |
</List> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment