Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react.lazy

import React, { Suspense } from 'react';
import Tabs from './Tabs';
import Glimmer from './Glimmer';

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

function MyComponent() {
  const [tab, setTab] = React.useState('photos');
  
  function handleTabSelect(tab) {
    setTab(tab);
  };

  return (
    <div>
      <Tabs onTabSelect={handleTabSelect} />
      <Suspense fallback={<Glimmer />}>
        {tab === 'photos' ? <Photos /> : <Comments />}
      </Suspense>
    </div>
  );
}

/*
In this example, if tab gets changed from 'photos' to 'comments', 
  but Comments suspends, the user will see a glimmer. 
  This makes sense because the user no longer wants to see Photos, 
    the Comments component is not ready to render anything, 
      and React needs to keep the user experience consistent, 
        so it has no choice but to show the Glimmer above.

However, sometimes this user experience is not desirable. 
In particular, it is sometimes better to show the “old” UI while 
  the new UI is being prepared. You can use the new startTransition 
API to make React do this:
*/

function handleTabSelect(tab) {
  startTransition(() => {
    setTab(tab);
  });
}
Source by reactjs.org #
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
7+6 =