Lazy loading and code splitting in React

Md Yusuf - Sep 30 - - Dev Community

Lazy loading and code splitting in React help optimize performance by loading only the necessary parts of your application, reducing initial load times. Here's how they work:

1. Lazy Loading

Lazy loading defers the loading of components until they are needed. In React, this is done using React.lazy() and Suspense.

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  • React.lazy(): Dynamically imports a component.
  • Suspense: Renders a fallback (e.g., a loading indicator) while the lazy-loaded component is being fetched.

2. Code Splitting

Code splitting breaks your bundle into smaller chunks, loading them on-demand. Webpack, used by React’s build system, automatically creates split points.

  • Dynamic Imports: You can use dynamic import() to load modules only when needed. For example:
import("./module").then(module => {
  // Use the dynamically loaded module
});
Enter fullscreen mode Exit fullscreen mode
  • React Router and Code Splitting: When using React Router, lazy load route components for better performance.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense } from 'react';

const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route path="/about" component={About} />
          <Route path="/" component={Home} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Improved Load Time: Only the necessary code is loaded when required.
  • Optimized Performance: Code splitting ensures that users only download the parts of the app they interact with.

Would you like a practical example or help implementing this in your project?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player