Code Splitting
Writing and shipping native ESM allows you to take advantage of some pretty neat optimisation features. Dynamic imports and the lazy
API can be used to import components on the fly, in a way that is compatible with Suspense
.
import { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent.jsx'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
When both server and client rendering this component, the OtherComponent.jsx
will only be imported when requested. Native code-splitting? YES!
Hot tip!Using
lazy
imports with Routing is one of the best things ever