DEV Community

Cover image for Prefetch lazy-loaded component

Prefetch lazy-loaded component

Sung M. Kim on November 30, 2019

Cory House has posted following tweet today. Cory House @housecor ...
Collapse
 
maddhruv profile image
Dhruv Jain

With a very small modification we can add support for prefetching to the wrapper lazy load function with retry.

// Lazy with Retry and Prefetching
export const lazyWithRetryAndPrefetching = (componentImport) => {
  const factory = async () => {
    try {
      return await componentImport();
    } catch (error) {
      console.error(error);
      return window.location.reload();
    }
  };

  const Component = lazy(factory);

  Component.prefetch = factory;

  return Component;
};
Enter fullscreen mode Exit fullscreen mode

Deterministically prefetching is as easy as

// App.jsx
const Material = lazyWithRetryAndPrefetching(() => import("./Material"));

useEffect(() => {
    Material.prefetch();
}, []);
Enter fullscreen mode Exit fullscreen mode

Checkout more details at

Collapse
 
fly profile image
joon • Edited

Possibly too technical yet to apply to any of my current projects, but definitely something that I will try in the future. Thank you for the post :)

Collapse
 
dance2die profile image
Sung M. Kim

Thank you, joon and glad to have found it useful.

This post also serves as a #devjournal to remind myself and get back to :)

Collapse
 
httpjunkie profile image
Eric Bishard

I came here for the Koala! didn't even read the article! OK, I'll read the article. But let it be known I came for the Koala image...

Collapse
 
dance2die profile image
Sung M. Kim

So long as the image peaked your interest, I am fine 😁

Collapse
 
lineldcosta profile image
lineldcosta

Awesome tip!

Collapse
 
dance2die profile image
Sung M. Kim

Thanks~