bunny
bunny

Reputation: 2037

How to lazy load a react component

Suppose I need to build a home page and I want the h1 and p to be rendered first and if the user scroll to the area of MyComponent, MyComponnet gets rendered or the async call in MyComponent does not prevent h1 or p rendering so that to have a better user experience. Is there a way I can do it?

const Home = () => {
return <div>
 <h1>Home Page</h1>
 <p>aaaaaaaaaa</p>
 <p>aaaaaaaaaa</p>
 <p>aaaaaaaaaa</p>
 <MyComponent />
</div>;
}


const MyComponent = () => {
 const res = await fetch('some url...');
 // ... some code process the res
 const data = processRes(res);
 return <div>data</div> 
}

Upvotes: 0

Views: 94

Answers (1)

Karthik R
Karthik R

Reputation: 5786

React is evolving for such use cases for enhanced experience and currently it's in experimental phase.

https://reactjs.org/docs/concurrent-mode-intro.html

Having said that, yours can be achieved with minor changes.

const MyComponent = React.lazy(() => import('./MyComponent')); // load lazy
return (
<>
  <h1></h1>
  <p></p>  
  <Suspense fallback={<SplashScreen/>}>
    <MyComponent/>
  </Suspense>
</>);

Upvotes: 1

Related Questions