Saturday, 5 October 2024

React Suspense

 how to handle fallback content while asynchronous actions are pending and encapsulate any portion of your component tree


<Suspense fallback={<LeoFallback />}>

  <LeoComponent />

</Suspense>

First, import the Suspense components from React, as well as any components you intend to load lazily.


import { Suspense } from 'react';


Then use lazy() to define a dynamic import. For the component you wish to load slowly, this function accepts an argument that is a function that produces a dynamic import statement.


const LeoComponent = lazy(() => import('./LeoComponent'));


  • After React loads, a component tree is rendered.
  • React looks to see whether any of its child components are in a suspended state when it comes across a Suspense component.
  • React will display the given fallback UI until the data is ready, if a child component is awaiting data (for example, as a result of a lazy() import or a data fetch).
  • React smoothly transitions to rendering the real content once the data is available.

No comments:

Post a Comment