Lazy Loading React Components
A helper function to streamline lazy loading components in React. The function returns an anonymous React component that prepares and resolves the import. When the import is in flight; a fallback is displayed until the import has finished loading.
This is a simple way to introduce intentional code splitting to a React project. This is a good technique to use with app routing. If users don’t visit a page; then the code for that page is never loaded.
// Helperimport { lazy, Suspense } from 'react';
function LazyLoadFallback() { return (<span>Loading...</span>);}
const lazyLoadComponent = (componentImport) => { const Component = lazy(componentImport); return (props) => { return ( <Suspense fallback={<LazyLoadFallback />}> <Component {...props} /> </Suspense> ); }}
export default lazyLoadComponent;// Usageimport AppHeader from './AppHeader';import AppFooter from './AppFooter';
import lazyLoadComponent from './lazyLoadComponent';const AppContent = lazyLoadComponent(() => import('./AppContent'));
function App() { return ( <> <AppHeader /> <AppContent /> </AppFooter> </> );}
export default App;Note; React lazy is doing some static analysis behind the scenes to make this work. Ideally; just an import path would be provided and the helper would handle the import too. The main drawback with this; is the path has to be relative to the helper function file, instead of the where the helper is being called. This would make the function more cumbersome to use in a project.