0

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> 
}
1
  • Set a loading state whenever you start the fetch and then set that state to false after it completes or fails. After the hooks, put an early return that will show "loading" or something else if that loading state is still true and then return the real component after the state is set to false. Or wait for React.suspense to be finished which encapsulates the pattern for you in a "React aware" way. Commented Aug 4, 2020 at 22:34

1 Answer 1

1

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>
</>);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.