Lazy loading components in ReactJS

amythical

amythical

Posted on May 18, 2024

Lazy loading components in ReactJS

Why should you lazy load components?

TLDR - For optimised chunk sizes and page load time.

I'll share my experience. My chunk sizes in the React production build were huge, much larger than the usual sizes.
React 16/Webpack 4 so unfortunately the good utilities like bundle analyzer would not work, so I glanced through the chunks' javascript code.
All the static imports were included in them, bloating the size of the common chunks used by the modules.

I refactored the code by late loading components which were not used/rendered on the screen on initial load. There were components which were loaded after the users actions like button clicks or scrolls, which were lazy loaded when needed.
This reduced my chunk size and also that led to a quicker load time of my page.

How to lazy load components -

  • React SSR - For SSR, '@loadable' is recommended.
import  loadable  from  '@loadable/component';

// using it when needed 
const  myReactComponent = loadable(() =>  import(`../../components/MyReactComponent`));
Enter fullscreen mode Exit fullscreen mode
  • React Lazy and Suspense
import Suspense from react;

class Test {
   constructor(){

   }

   someFunction(){
    // Import here and not statically
    const myReactComponent = React.lazy(() => 
    import(`../MyReactComponent`));
    this.setState({myReactComponent:myReactComponent});
  }

  render(){
    return (
      <Suspense fallback={<div>Loading...</div>}>
    <this.state.myReactComponent>
    </this.state.myReactComponent>
      </Suspense>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

The fallback attribute takes in a markup which can have text/loaders or another component.

Cheers.

💖 💪 🙅 🚩
amythical
amythical

Posted on May 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related