react-lazy-load-component
A react component that allows lazy components to load once they are in viewpoint. It uses the IntersectionObserver. Once a component is triggered to load, it will stay loaded (does not unload).
Motivation
Often for large pages it would be ideal to not load components below the fold to improve performance.
Installation
npm install react-lazy-load-component
Please note that this hook declares react
and as peer dependency. Therefore, you must have
react
installed to use this package.
Note: This hook relies on Intersection Observer API and hence if you want to use it in a browser that doesn't support it, the onus of shipping the polyfill is on the developer.
Example usage
A CRA based example app (which is also used in the test suite) can be found under examples/cra. Inline examples showcasing use-cases are below.
Example 1: Element with its parent document as viewport
As soon as at least 1px of the child element is visible in the parent document viewport,
isInViewport
evaluates to true.
import React from 'react'import ReactDOM from 'react-dom'import LazyLoadComp from 'react-lazy-load-component' const MyBigComponent = React; // your component to load { return <LazyLoadComp = ="300" ="300"> <MyBigComponent/> </LazyLoadComp> }
API
react-lazy-load-component props