Top Related Projects
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.
:hourglass_flowing_sand: A higher order component for loading components with promises.
React scrollbars component
React components for efficiently rendering large lists and tabular data
Essential React custom hooks ⚓ to super charge your components!
Quick Overview
react-lazyload
is a React component that lazily loads content when it becomes visible, reducing the initial load time and improving the overall performance of a web application. It is designed to work seamlessly with React and provides a simple and flexible API for developers to integrate lazy loading into their projects.
Pros
- Performance Optimization:
react-lazyload
helps to improve the initial load time of a web application by only loading content that is visible to the user, reducing the overall amount of data that needs to be downloaded. - Flexible Configuration: The library offers a wide range of configuration options, allowing developers to customize the lazy loading behavior to fit their specific use cases.
- Cross-browser Compatibility:
react-lazyload
is designed to work across a wide range of modern browsers, ensuring a consistent user experience. - Easy Integration: The library provides a straightforward API that makes it easy to integrate lazy loading into existing React projects.
Cons
- Potential Flicker: In some cases, the lazy loading process may cause a brief flicker or delay in the content being displayed, which could be noticeable to users.
- Dependency on React:
react-lazyload
is a React-specific library, which means it may not be suitable for non-React projects or for projects that use a different JavaScript framework. - Limited Support for Server-side Rendering: While
react-lazyload
does support server-side rendering, the implementation may be more complex and require additional configuration. - Potential Performance Impact: Depending on the specific use case and implementation, the use of
react-lazyload
could potentially have a negative impact on the overall performance of the application if not used correctly.
Code Examples
Here are a few examples of how to use react-lazyload
in a React project:
import React from 'react';
import LazyLoad from 'react-lazyload';
// Lazy load an image
<LazyLoad>
<img src="my-image.jpg" alt="My Image" />
</LazyLoad>
// Lazy load a component
<LazyLoad>
<MyComponent />
</LazyLoad>
// Customize the lazy loading behavior
<LazyLoad
once // Load the content only once
offset={100} // Load the content when it's 100px away from the viewport
placeholder={<div>Loading...</div>} // Display a placeholder while the content is loading
>
<MyComponent />
</LazyLoad>
Getting Started
To get started with react-lazyload
, follow these steps:
- Install the library using npm or yarn:
npm install react-lazyload
- Import the
LazyLoad
component and use it to wrap the content you want to lazy load:
import React from 'react';
import LazyLoad from 'react-lazyload';
const MyComponent = () => {
return (
<div>
<h1>My Component</h1>
<LazyLoad>
<img src="my-image.jpg" alt="My Image" />
</LazyLoad>
</div>
);
};
- Customize the lazy loading behavior by passing props to the
LazyLoad
component:
<LazyLoad
once // Load the content only once
offset={100} // Load the content when it's 100px away from the viewport
placeholder={<div>Loading...</div>} // Display a placeholder while the content is loading
>
<MyComponent />
</LazyLoad>
- Refer to the project's documentation for more advanced usage and configuration options.
Competitor Comparisons
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.
Pros of react-intersection-observer
- Flexible API: react-intersection-observer provides a flexible API that allows for customization of the intersection observer's behavior, such as setting the root element, threshold, and root margin.
- Supports SSR: The library is designed to work with server-side rendering (SSR), making it a suitable choice for applications that require this functionality.
- Lightweight: react-intersection-observer is a relatively lightweight library, with a small footprint and minimal dependencies.
Cons of react-intersection-observer
- Requires Polyfill: The library relies on the Intersection Observer API, which is not supported in all browsers. This may require the use of a polyfill to ensure compatibility.
- Limited Functionality: Compared to react-lazyload, react-intersection-observer has a more limited set of features, such as the lack of built-in support for image loading and placeholder rendering.
Code Comparison
react-lazyload:
<LazyLoad height={200} offset={100}>
<img src="https://example.com/image.jpg" alt="Example" />
</LazyLoad>
react-intersection-observer:
<Observer>
{({ inView, ref }) => (
<div ref={ref}>
{inView && <img src="https://example.com/image.jpg" alt="Example" />}
</div>
)}
</Observer>
:hourglass_flowing_sand: A higher order component for loading components with promises.
Pros of React Loadable
- Dynamic Imports: React Loadable supports dynamic imports, allowing for efficient code splitting and lazy loading of components.
- Customizable Loading State: React Loadable provides a flexible API to customize the loading state, including the ability to display a loading component or handle errors.
- Server-Side Rendering (SSR) Support: React Loadable is designed to work seamlessly with server-side rendering, ensuring a smooth user experience.
Cons of React Loadable
- Complexity: React Loadable has a more complex API compared to React LazyLoad, which may require more setup and configuration.
- Dependency on Webpack: React Loadable relies on Webpack's dynamic import functionality, which may not be suitable for all project setups.
Code Comparison
React LazyLoad:
import LazyLoad from 'react-lazyload';
<LazyLoad>
<MyComponent />
</LazyLoad>
React Loadable:
import Loadable from 'react-loadable';
const MyComponent = Loadable({
loader: () => import('./MyComponent'),
loading: () => <div>Loading...</div>,
});
React scrollbars component
Pros of react-custom-scrollbars
- Provides a highly customizable scrollbar component with a wide range of styling options.
- Supports both vertical and horizontal scrollbars, as well as auto-hiding scrollbars.
- Includes built-in support for touch devices and smooth scrolling.
Cons of react-custom-scrollbars
- May be overkill for simple scrolling needs, as it provides more features than some users may require.
- Requires more setup and configuration compared to a simpler scrolling solution like react-lazyload.
Code Comparison
react-lazyload (twobin/react-lazyload):
<LazyLoad height={200}>
<img src="https://example.com/image.jpg" alt="Example" />
</LazyLoad>
react-custom-scrollbars (malte-wessel/react-custom-scrollbars):
<Scrollbars
style={{ height: 200 }}
autoHide
autoHideTimeout={1000}
autoHideDuration={200}
>
<div>Scrollable content</div>
</Scrollbars>
React components for efficiently rendering large lists and tabular data
Pros of react-window
- Performance: react-window is designed to be highly performant, with a focus on efficient rendering and memory usage.
- Flexibility: react-window provides a flexible API that allows for customization and integration with various UI frameworks.
- Virtualization: react-window implements virtualization, which can significantly improve performance for large datasets.
Cons of react-window
- Limited Functionality: react-window is primarily focused on virtualization and may lack some of the advanced features found in react-lazyload.
- Steeper Learning Curve: The API of react-window may be more complex and require more setup compared to react-lazyload.
Code Comparison
react-lazyload:
<LazyLoad height={500}>
<img src="https://example.com/image.jpg" alt="Example" />
</LazyLoad>
react-window:
<FixedSizeList
height={500}
itemCount={100}
itemSize={50}
width={300}
>
{({ index, style }) => (
<div style={style}>Item {index}</div>
)}
</FixedSizeList>
Essential React custom hooks ⚓ to super charge your components!
Pros of Rooks
- Comprehensive Hooks Library: Rooks provides a wide range of hooks, covering various use cases, making it a more comprehensive solution compared to react-lazyload.
- Actively Maintained: Rooks has a more active development community, with frequent updates and bug fixes.
- Extensive Documentation: Rooks has detailed documentation, making it easier for developers to understand and use the library.
Cons of Rooks
- Larger Footprint: Rooks has a larger bundle size compared to react-lazyload, which may be a concern for projects with strict size constraints.
- Steeper Learning Curve: The extensive feature set of Rooks may make it more complex to learn and integrate into a project, compared to the more focused react-lazyload.
Code Comparison
react-lazyload:
<LazyLoad>
<img src="my-image.jpg" alt="My Image" />
</LazyLoad>
Rooks:
import { useIntersection } from 'rooks';
const MyComponent = () => {
const { entry, ref } = useIntersection();
return (
<div ref={ref}>
{entry?.isIntersecting && <img src="my-image.jpg" alt="My Image" />}
</div>
);
};
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Note
This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help.
react-lazyload
Lazyload your Components, Images or anything matters the performance.
Why it's better
- Take performance in mind, only 2 event listeners for all lazy-loaded components
- Support both
one-time lazy load
andcontinuous lazy load
mode scroll
/resize
event handler is throttled so you won't suffer frequent update, you can switch to debounce mode too- Decorator supported
- Server Side Rendering friendly
- Thoroughly tested
Installation
2.0.0 is finally out, read Upgrade Guide, it's almost painless to upgrade! 3.0.0 fixes the findDomNode warning through usage of React ref, and the following are the changes you need to be aware of
- Now we have an extra div wrapping the lazy loaded component for the React ref to work
- We can understand that it is an extra DOM node, and we are working to optimize that if possible
- It might break your UI or snapshot tests based on your usage
- To customize the styling to the extra div please refer here
- Found any other problem, please feel free to leave a comment over here
$ npm install --save react-lazyload
Usage
import React from 'react';
import ReactDOM from 'react-dom';
import LazyLoad from 'react-lazyload';
import MyComponent from './MyComponent';
const App = () => {
return (
<div className="list">
<LazyLoad height={200}>
<img src="tiger.jpg" /> /*
Lazy loading images is supported out of box,
no extra config needed, set `height` for better
experience
*/
</LazyLoad>
<LazyLoad height={200} once >
/* Once this component is loaded, LazyLoad will
not care about it anymore, set this to `true`
if you're concerned about improving performance */
<MyComponent />
</LazyLoad>
<LazyLoad height={200} offset={100}>
/* This component will be loaded when it's top
edge is 100px from viewport. It's useful to
make user ignorant about lazy load effect. */
<MyComponent />
</LazyLoad>
<LazyLoad>
<MyComponent />
</LazyLoad>
</div>
);
};
ReactDOM.render(<App />, document.body);
If you want to have your component lazyloaded by default, try this handy decorator:
import { lazyload } from 'react-lazyload';
@lazyload({
height: 200,
once: true,
offset: 100
})
class MyComponent extends React.Component {
render() {
return <div>this component is lazyloaded by default!</div>;
}
}
Special Tips
You should be aware that your component will only be mounted when it's visible in viewport, before that a placeholder will be rendered.
So you can safely send request in your component's componentDidMount
without worrying about performance loss or add some pretty entering effects, see this demo for more detail.
Props
children
Type: Node Default: undefined
NOTICE Only one child is allowed to be passed.
scrollContainer
Type: String/DOM node Default: undefined
Pass a query selector string or DOM node. LazyLoad will attach to the window object's scroll events if no container is passed.
height
Type: Number/String Default: undefined
In the first round of render, LazyLoad will render a placeholder for your component if no placeholder is provided and measure if this component is visible. Set height
properly will make LazyLoad calculate more precisely. The value can be number or string like '100%'
. You can also use css to set the height of the placeholder instead of using height
.
once
Type: Bool Default: false
Once the lazy loaded component is loaded, do not detect scroll/resize event anymore. Useful for images or simple components.
offset
Type: Number/Array(Number) Default: 0
Say if you want to preload a component even if it's 100px below the viewport (user have to scroll 100px more to see this component), you can set offset
props to 100
. On the other hand, if you want to delay loading a component even if it's top edge has already appeared at viewport, set offset
to negative number.
Library supports horizontal lazy load out of the box. So when you provide this prop with number like 100
it will automatically set left edge offset to 100
and top edge to 100
;
If you provide this prop with array like [100, 200]
, it will set left edge offset to 100
and top offset to 200
.
scroll
Type: Bool Default: true
Listen and react to scroll event.
resize
Type: Bool Default: false
Respond to resize
event, set it to true
if you do need LazyLoad listen resize event.
NOTICE If you tend to support legacy IE, set this props carefully, refer to this question for further reading.
overflow
Type: Bool Default: false
If lazy loading components inside a overflow container, set this to true
. Also make sure a position
property other than static
has been set to your overflow container.
placeholder
Type: Any Default: undefined
Specify a placeholder for your lazy loaded component.
If you provide your own placeholder, do remember add appropriate height
or minHeight
to your placeholder element for better lazyload performance.
unmountIfInvisible
Type: Bool Default: false
The lazy loaded component is unmounted and replaced by the placeholder when it is no longer visible in the viewport.
debounce/throttle
Type: Bool / Number Default: undefined
Lazyload will try to use passive event by default to improve scroll/resize event handler's performance. If you prefer control this behaviour by yourself, you can set debounce
or throttle
to enable built in delay feature.
If you provide a number, that will be how many ms
to wait; if you provide true
, the wait time defaults to 300ms
.
NOTICE Set debounce
/ throttle
to all lazy loaded components unanimously, if you don't, the first occurrence is respected.
classNamePrefix
Type: String Default: lazyload
While rendering, Lazyload will add some elements to the component tree in addition to the wrapped component children.
The classNamePrefix
prop allows the user to supply their own custom class prefix to help:
# Avoid class conflicts on an implementing app
# Allow easier custom styling
These being: # A wrapper div, which is present at all times (default )
style
Type: Object Default: undefined
Similar to classNamePrefix, the style
prop allows users to pass custom CSS styles to wrapper div.
wheel
DEPRECATED NOTICE
This props is not supported anymore, try set overflow
for lazy loading in overflow containers.
Utility
forceCheck
It is available to manually trigger checking for elements in viewport. Helpful when LazyLoad components enter the viewport without resize or scroll events, e.g. when the components' container was hidden then become visible.
Import forceCheck
:
import { forceCheck } from 'react-lazyload';
Then call the function:
forceCheck();
forceVisible
Forces the component to display regardless of whether the element is visible in the viewport.
import { forceVisible } from 'react-lazyload';
Then call the function:
forceVisible();
Scripts
$ npm run demo:watch
$ npm run build
Who should use it
Let's say there is a fixed
date picker on the page, when user picks a different date, all components displaying data should send ajax requests with new date parameter to retreive updated data, even many of them aren't visible in viewport. This makes server load furious when there are too many requests in one time.
Using LazyLoad
component will help ease this situation by only updating components visible in viewport.
Contributors
License
MIT
Top Related Projects
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.
:hourglass_flowing_sand: A higher order component for loading components with promises.
React scrollbars component
React components for efficiently rendering large lists and tabular data
Essential React custom hooks ⚓ to super charge your components!
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot