Socket
Socket
Sign inDemoInstall

react-lazy-with-preload

Package Overview
Dependencies
0
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-lazy-with-preload


Version published
Maintainers
1
Install size
6.43 kB
Created

Readme

Source

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

npm install react-lazy-with-preload

Usage

Before:

import { lazy, Suspense } from "react";
const OtherComponent = lazy(() => import("./OtherComponent"));

After:

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:

function SomeComponent() {
    const { showOtherComponent, setShowOtherComponent } = useState(false);

    return (
        <div>
            <Suspense fallback={<div>Loading...</div>}>
                {showOtherComponent && <OtherComponent />}
            </Suspense>
            <button
                onClick={() => setShowOtherComponent(true)}
                // This component will be needed soon. Let's preload it!
                onMouseOver={() => OtherComponent.preload()}
            >
                Click me to render OtherComponent
            </button>
        </div>
    );
}

Acknowledgements

Inspired by the preload behavior of react-loadable.

Keywords

FAQs

Last updated on 22 Aug 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc