What is @loadable/component?
@loadable/component is a library for React that allows you to dynamically load components. This can help improve the performance of your application by splitting your code into smaller chunks and loading them only when needed.
What are @loadable/component's main functionalities?
Dynamic Import
This feature allows you to dynamically import a component. The component will only be loaded when it is needed, which can help reduce the initial load time of your application.
import loadable from '@loadable/component';
const LoadableComponent = loadable(() => import('./MyComponent'));
function App() {
return (
<div>
<LoadableComponent />
</div>
);
}
Server-Side Rendering (SSR) Support
This feature provides support for server-side rendering. It allows you to collect and render the chunks needed for the initial render on the server, ensuring that the client can seamlessly continue rendering.
import { ChunkExtractor, ChunkExtractorManager } from '@loadable/server';
import { renderToString } from 'react-dom/server';
import App from './App';
const statsFile = path.resolve('./build/loadable-stats.json');
const extractor = new ChunkExtractor({ statsFile });
const jsx = extractor.collectChunks(<App />);
const html = renderToString(jsx);
const scriptTags = extractor.getScriptTags(); // or extractor.getScriptElements();
Prefetching
This feature allows you to prefetch components. Prefetching can help improve the user experience by loading components in the background before they are needed.
import loadable from '@loadable/component';
const LoadableComponent = loadable(() => import('./MyComponent'), {
cacheKey: () => 'MyComponent',
resolveComponent: (components) => components.MyComponent,
prefetch: true
});
function App() {
return (
<div>
<LoadableComponent />
</div>
);
}
Other packages similar to @loadable/component
react-loadable
react-loadable is another library for dynamically loading React components. It provides similar functionality to @loadable/component, including code splitting and server-side rendering support. However, @loadable/component is considered to be more modern and easier to use.
react-lazyload
react-lazyload is a library for lazy loading React components. It focuses on loading components only when they are about to enter the viewport. While it provides similar functionality to @loadable/component, it is more focused on lazy loading for performance optimization.
react-async
react-async is a library for handling asynchronous operations in React. It can be used to dynamically load components, but it also provides more general-purpose tools for managing async data fetching and state. It offers a broader range of features compared to @loadable/component.