Skip to content
Advertisement

React.lazy warning

// project/src/App.js
import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import {NavBar, Loading} from "./components";
import './index.css';

const Home = lazy(() => import('./components/home'));

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

export default App;

Other file.

// project/src/components/Home.js
import React from "react";

const Home = () => (
    <div className="home">
       ...
    </div>
);

export default Home;

The code works but () => import('./components/home') generates this warning:

Argument type function(): Promise<{readonly default?: function(): any}> is not assignable to parameter type () => Promise<{default: ComponentType}> Type Promise<{readonly default?: function(): any}> is not assignable to type Promise<{default: ComponentType}>

I have already read the other topics and none of them work. Thank you.

Advertisement

Answer

Although I don’t like to complicate things, to remove that warning you have to use this syntax:

const Home = lazy(() => import('./components/Home').then(({default: Home}) => ({default: Home})));
Advertisement