Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ianschmitz/react-lazy-with-preload
React.lazy() with preload support!
https://github.com/ianschmitz/react-lazy-with-preload
Last synced: about 2 months ago
JSON representation
React.lazy() with preload support!
- Host: GitHub
- URL: https://github.com/ianschmitz/react-lazy-with-preload
- Owner: ianschmitz
- License: mit
- Created: 2019-05-22T03:33:58.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-01-16T15:36:38.000Z (8 months ago)
- Last Synced: 2024-04-14T11:14:57.277Z (5 months ago)
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/react-lazy-with-preload
- Size: 1.03 MB
- Stars: 74
- Watchers: 3
- Forks: 7
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
`react-lazy-with-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 react-lazy-with-preload
```## Usage
**Before:**
```js
import { lazy, Suspense } from "react";
const OtherComponent = lazy(() => import("./OtherComponent"));
```**After:**
```js
import { Suspense } from "react";
import { lazyWithPreload } from "react-lazy-with-preload";
const OtherComponent = lazyWithPreload(() => import("./OtherComponent"));// ...
OtherComponent.preload();
```To preload a component before it is rendered for the first time, the component that is returned from `lazyWithPreload()` 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:
```js
function SomeComponent() {
const { showOtherComponent, setShowOtherComponent } = useState(false);return (
}>
Loading...
{showOtherComponent && }
setShowOtherComponent(true)}
// This component will be needed soon. Let's preload it!
onMouseOver={() => OtherComponent.preload()}
>
Click me to render OtherComponent
);
}
```## Acknowledgements
Inspired by the preload behavior of [react-loadable](https://github.com/jamiebuilds/react-loadable).