https://github.com/wscats/lazy-preload
Wraps the React.lazy API with preloaded functionality.
https://github.com/wscats/lazy-preload
lazy preload react
Last synced: about 2 months ago
JSON representation
Wraps the React.lazy API with preloaded functionality.
- Host: GitHub
- URL: https://github.com/wscats/lazy-preload
- Owner: Wscats
- License: mit
- Created: 2022-06-19T11:00:55.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-06-19T11:31:08.000Z (almost 3 years ago)
- Last Synced: 2025-04-14T23:13:44.710Z (about 2 months ago)
- Topics: lazy, preload, react
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/lazy-preload
- Size: 90.8 KB
- Stars: 39
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
`lazy-preload` wraps the `React.lazy()` API and adds the ability to preload the component before it is rendered for the first time.
## Install
```sh
npm install lazy-preload
```## Usage
**Before:**
```js
import {
lazy,
Suspense
} from "react";
const LazyLoadComponent = lazy(() => import("./LazyLoadComponent"));
```**After:**
```js
import {
Suspense
} from "react";
import {
lazyWithPreload
} from "lazy-preload";
const LazyLoadComponent = lazyWithPreload(() => import("./LazyLoadComponent"));// ...
LazyLoadComponent.preload();
```To preload a component before it is rendered for the first time, the component that is returned from `lazy()` has a `preload` function attached that you can invoke. `preload()` returns a `Promise` that you can wait on if needed. The promise is idempotent, meaning that `preload()` will return the same `Promise` instance if called multiple times.
For more information about React code-splitting, `React.lazy` and `React.Suspense` , see https://reactjs.org/docs/code-splitting.html.
## Example
For example, if you need to load a component when a button is pressed, you could start preloading the component when the user hovers over the button:
```tsx
import { lazyWithPreload, LazyLoadComponent } from 'lazy-preload';
const Component = lazyWithPreload(() => import("./component"));export function render() {
return Icon>}
loading={Loading}
lazyLoadComponent={Component}
>
}
```## Acknowledgements
Inspired by the preload behavior of [react-loadable](https://github.com/jamiebuilds/react-loadable) and [react-lazy-with-preload](https://github.com/ianschmitz/react-lazy-with-preload).