Blog>
Snippets

Code Splitting in React for Performance Optimization

Explains how to implement code splitting in a React application using dynamic import() syntax for lazy loading components, aiming to improve the app's performance.
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
This code demonstrates the initial setup for code splitting in a React application. React.lazy function is used to dynamically import a component, which is then stored in a variable. This component will only be loaded when it's rendered for the first time.
function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}
Here, the Suspense component from React is used to wrap the lazily-loaded component. The fallback prop is passed to Suspense, specifying what should be rendered while the lazy component is being loaded. This example displays a simple 'Loading...' message.