Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

Can Lazy Function in React Support Named Exports?

No, React.lazy does not support named exports directly.
React.lazy expects the module you are importing to have a default export. If your module only has named exports, React.lazy will not work out of the box and you will encounter an error.

Here's why:
When you use React.lazy, React expects the module to resolve to a component through a default export. Named exports are not automatically understood by React.lazy.


Example of correct usage (default export):

// MyComponent.js export default function MyComponent() { return <div>Hello from MyComponent</div>; }
// App.js import React, { Suspense } from 'react'; const MyComponent = React.lazy(() => import('./MyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <MyComponent /> </Suspense> ); } export default App;

What if you only have named exports?
If the module exports components by name, you have two options:

  1. Re-export with a default: Modify the module to add a default export.
// MyComponent.js export function MyComponent() { return <div>Hello from MyComponent</div>; } // Add this line export default MyComponent;
  1. Use a wrapper inside React.lazy: If you can't modify the original module, you can dynamically import the named export and re-export it as default inline:
const MyComponent = React.lazy(() => import('./MyComponent').then(module => ({ default: module.MyComponent })) );

In this way, you manually tell React.lazy which named export to treat as the default export.


Summary:

  • React.lazy requires a default export.
  • If your module only has named exports, either add a default export or map the named export to a default manually during dynamic import.