Home > Blockchain >  How to import a component later?
How to import a component later?

Time:06-13

I'm trying to import components with a delay. I want to import the components quietly. While looking at the home page, the back components will load silently.

I tried lazy loading, but this option returned me the page every time I logged in for a longer time.

const SignUp = lazy(async () => {
 await new Promise(resolve => setTimeout(resolve, 5000));
 return import('../sign-up/sign-up').then(({ SignUp }) => ({ default: SignUp }));});

How can I solve it?

thanks.

CodePudding user response:

React.lazy() is a new function in react that lets you load react components lazily through code splitting without help from any additional libraries. Lazy loading is the technique of rendering only-needed or critical user interface items first , then quietly unrolling the non-critical items later.

Suspense is a component required by the lazy function basically used to wrap lazy components.

Solution for Using React Suspense (React 16.6 ) version

import React, { Suspense } from "react";
const Customer = React.lazy(() => import("./Customer.js"));
const Admin = React.lazy(() => import("./Admin.js"));

//Instead of regular import statements, we will use the above approach for lazy loading
export default (props) => {
    if (props.user === "admin") {
        return (
            // fallback component is rendered until our main component is loaded
            <Suspense fallback={<div>Loading</div>}>
                <Admin />
            </Suspense>
        );
    } else if (props.user === "customer") {
        return (
            <Suspense fallback={<div>Loading</div>}>
                <Customer />
            </Suspense>
        );
    } else {
        return <div> Invalid User </div>;
    }
};

Without React Suspense

Our calling component, in this case Home.js

import React from "react";
import { lazyLoader } from "./lazyLoader";

const Customer = lazyLoader(() => import("./Customer.js"));
const Admin = lazyLoader(() => import("./Admin.js"));

//Instead of regular import statements, we will use the above approach for lazy loading

export default (props) => {
    if (props.user === "admin") {
        return <Admin />;
    } else if (props.user === "customer") {
        return <Customer />;
    } else {
        return <div> Invalid User </div>;
    }
};

And lazyLoader.js

const lazyLoader = (importComp, fallback) => {
    return class extends React.Component {
        state = {
            component: null, //initializing state
        };

        //loading the component and setting it to state
        componentDidMount() {
            importComp().then((comp) => setState({ component: comp.default }));
        }

        //rendering the component
        render() {
            const C = this.state.component;
            return C ? (
                <C {...this.props} />
            ) : fallback ? (
                fallback
            ) : (
                <div>loading</div>
            );
            // If component is not loaded then return fallback component, if fallback is not provided then use default loading
        }
    };
};
export default lazyLoader;

CodePudding user response:

So there are three ways to lazy load component you can check my repo here https://github.com/amansadhwani/all-features-react/tree/master/src/components/LazyLoading

/* 1)Naive lazy load */
     const Chart = lazy(() => import("./AnyComponent")); // this will load on demand when needed

 /*2) Lazy load with prefetch */
      const Chart = lazy(() => import(/* webpackPrefetch: true */ "./AnyComponent")); // this will load after everything is completed in short at the end of everything it will load

/*3) Predictive lazy load */
     const loadComponent = () => import("./AnyComponent");
     const Comp= lazy(loadComponent ); // this is something you will load as soon as someone hover's over any button you will attach event listners onFocus and onm ouseEnter as shown below 

    onFocus={Comp}
    onm ouseEnter={Comp}
  • Related