The Legend of Zelda triforce

Frontend Techniques in the Realm of Hyrule with React

Code Splitting

Triforce

Feed

Triforce
Ganondorf's profile picture

Ganondorf @ganon_dorf · 2024-07-03

Planning my next move...

Zelda's profile picture

Zelda @zelda · 2024-07-02

Defeated Ganon and restored peace to Hyrule.

Mipha's profile picture

Mipha @mipha · 2024-07-09

Healing my friends with Mipha's Grace.

Urbosa's profile picture

Urbosa @urbosa · 2024-07-08

Training hard to master Urbosa's Fury.

Link's profile picture

Link @link_hero · 2024-07-01

Just found the Master Sword in the Lost Woods!

Impa's profile picture

Impa @impa · 2024-07-10

Researching ancient Sheikah technology.

Prince Sidon's profile picture

Prince Sidon @sidon · 2024-07-05

Helped Link defeat the Divine Beast Vah Ruta.

Daruk's profile picture

Daruk @daruk · 2024-07-07

Protected my friends with Daruk's Protection today.

Revali's profile picture

Revali @revali_the_great · 2024-07-06

My flight skills are unmatched. Watch out, Ganon!

Beedle's profile picture

Beedle @buy_from_beedle · 2024-07-04

Come buy from Beedle! Best deals in Hyrule!

1. What is Code Splitting ?

Instead of loading an entire app at once, code splitting allows parts of the app to be loaded on demand.

Benefits:

  • ✅ Improves performance
  • ✅ Lowers initial load time

2. Lazy loading components in React

lazy is used to enabled code splitting at the component level

  • Returns the component you want to render
  • If the component is still loading when it’s called to render, it will suspend and the <Suspense> component can be used to show a loading indicator
const LazyComponent = React.lazy(() => import("./Component"));

3. The Suspense component

When lazy loading a component, wrap it in <Suspense> to define a UI fallback that will be displayed while the component is loading.

// lazy load PostComment component until the request to view comments

const PostComments = lazy(() => import('./PostComment'))

const Post = () => {
  return(
    // ...
      {showComments && (
        <Suspense fallback={<Loading />}>
          {commentList.map((comment) => (
            <PostComment props={props} />
          ))}
        </Suspense>
      )}
    // ...
  )
}

4. Use cases for lazy and <Suspense>

  • Lazy loading large or rarely used components
  • Loading route based component in a single page app
  • Delaying the load time of heavy libraries
  • Reducing initial load time of the application

5. A few caveats

⚠️ <Suspense> does not detect when data is being fetched inside of an effect or event handler

⚠️ Only suspense-enabled data sources will activate the <Suspense> component. These include:

  • Data fetching with suspense-enabled frameworks like Next and Remix
  • Loading components with lazy()
  • Reading the value of a promise with use