Instead of manually handling the promise returned by import() by returning the default export and setting state, you can lean on the lazy() API. This function takes a function that returns an import() promise. The return value is a lazy component that you can just render. Let's modify the App component to use this API:
import React, { Suspense, lazy } from "react";
const MyComponent = lazy(() => import("./MyComponent"));
export default function App() {
return (
<Suspense fallback={"loading..."}>
<MyComponent />
</Suspense>
);
}
The MyComponent value is created by calling lazy(), passing in the dynamic module import as an argument. Now, you have a separate bundle for your component and a lazy component that loads the bundle when it's first rendered. There's one other thing that we need here. The Suspense component compliments lazy components by providing a fallback to display while the code...