Vivek Singh
Vivek Singh

Reputation: 646

Next/React lazy load not working as expected for components

Hi all I am new in Next/react I am trying to lazy load one component. What my expectation is that component must loads when it is visible in user view port or once a page is fully rendered. Its html code should not come in the first response. But after debugging I found that it is not working as expected.

I have tried below approaches

index.js

const ProductTabbedWidget = React.lazy(() => import('../../../components/ProductSearch/ProductTabbed/ProductTabbedWidget'));

and

const ProductTabbedWidget = dynamic(() => import('../../../components/ProductSearch/ProductTabbed/ProductTabbedWidget'),{suspense:true,});

<Suspense fallback={<div>Loading</div>}>
<ProductTabWidget vehicleType={type}></ProductTabWidget>
</Suspense>

Component: ProductTabbedWidget

const ProductTabWidget = (props) => {

const getData = () =>{
// fetch the data from api 
// ex. locahost:7000/api/get-data
}
useEffect(()=>{
  getData()
},[])
return (
    <div></div>
)

}

The call to this api is visible in chrome when the page loads. I am confused if react lazy is the rigt way to do this. I know this can be done using javascript but is there any way to do it ony by react or next. I have gone through these answers but none of them works.

React suspense/lazy delay?

How to know if React lazy load component is working or not? React js react React lazy loading - when to use

Upvotes: 0

Views: 2767

Answers (1)

Keval Rana
Keval Rana

Reputation: 21

In react side use lazy loading like this.

import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

In Next JS

import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() =>
  import('../components/hello').then((mod) => mod.Hello)
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponent />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home

Upvotes: 0

Related Questions