DEV Community

Jayant
Jayant

Posted on

Dynamic Imports

WHAT

It is a optimization technique that allows loading a module only when it is needed.
This decreases the initial bundle size and improves the startup time of the application.

Consider example of a Emoji Picker Component in a chat app that won't be used by many peoples.

However, there are some trade-offs to consider.

  • User has to wait for the module to load.
  • Adding additional dependency to the application @loadable/component is required for SSR as React.suspense & React.lazy are not supported.

How

1) Using React.lazy & React.suspense

Note -

  • Only works for CSR.
  • The Component you are dynamically importing must have default export.
  • Lazy returns a Promise that resolves to a module.
import React, { Suspense } from 'react';

const EmojiPicker = React.lazy(()=>import("./emojiPicker.tsx"));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <EmojiPicker />
      </Suspense>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

2) Using @loadable/component

yarn add @loadable/component 
Enter fullscreen mode Exit fullscreen mode

The syntax is similar we just have to pass the fallback UI in the loadable function only.
Also it works with Suspense also but as suspense didn't work in SSR use carefully.

import React, { Suspense } from 'react';
import loadable from "@loadable/component";

const EmojiPicker = loadable(()=>import("./emojiPicker.tsx"),{
    fallback:<div>Loading...</div>
});

function MyComponent() {
  return (
    <div>
        <input type="text" placeholder="Type a message..." />
        {openEmojiPicker && <EmojiPicker />}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)