39. What is code splitting in React?
hard

Code splitting is a performance optimization technique in React that breaks the JavaScript bundle into smaller chunks to reduce initial load time and improve application performance.

Explanation of Key Concepts

  • Lazy Loading: Loading components or modules only when they're needed.
  • Dynamic Import() Statements: Loading JavaScript modules on demand using import().
  • React.lazy: A built-in helper for code splitting React components.
  • React.Suspense: Wraps lazy-loaded components and handles loading states.

Step-by-Step Solution

  1. Lazy load components or modules: Use React.lazy to split code into separate chunks, like const LazyComponent = lazy(() => import('./MyComponent'));
  2. Wrap with Suspense: Provide a fallback UI while the chunk is being loaded using Suspense, like {`Loading...
}> `}.

Example: Lazy Loading with Suspense

import React, { Suspense, lazy } from 'react';

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

const App = () => {
  return (
    <div>
      <h1>Main App</h1>
      {/* Show fallback while LazyComponent is loading */}
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
};

Common Use Cases

  • Large components: Only load when needed in specific routes or conditions.
  • Third-party libraries: Not required immediately (e.g., charts, editors).
  • Route-based code splitting: Using tools like React Router.

Best Practices

  • Split code by route or feature to maximize benefits.
  • Always provide a fallback UI with Suspense.
  • Combine with React Router for effective page-level splitting.
  • Use bundlers like webpack or Vite to support chunk generation behind the scenes.

Conclusion

Code splitting in React improves performance by reducing JavaScript sent upfront. By leveraging React.lazy and Suspense, developers can create faster, more scalable apps that load only what is needed.