Blog>
Snippets

Dynamic Import with Loading State

Demonstrate how to dynamically import modules with Next.js 14 while providing a loading UI when the module is being loaded with suspense components.
import { useState, Suspense } from 'react';

function MyComponent() {
  // State to handle the dynamic import
  const [Module, setModule] = useState(null);

  // Function to load the module dynamically
  const loadModule = async () => {
    if (!Module) {
      // Begin loading the module
      const loadedModule = await import('./DynamicModule');
      // Once the module is loaded, update the state
      setModule(() => loadedModule.default);
    }
  };

  return (
    // Use Suspense to provide a loading fallback
    <Suspense fallback={<div>Loading...</div>}>
      <button onClick={loadModule}>Load Module</button>
      // Render the dynamically loaded module
      {Module && <Module />}
    </Suspense>
  );
}
This code snippet demonstrates how to use React's Suspense component in conjunction with useState hook to handle dynamic imports and show a loading state in the UI. Suspense allows you to specify a fallback component to display while waiting for the dynamic import, providing a smoother user experience.