I am trying to use React.lazy for code splitting in my TypeScript React app.
All I am doing is changing that line:
import {ScreensProductList} from "./screens/Products/List";
to this line:
const ScreensProductList = lazy(() => import('./screens/Products/List'));
But the import('./screens/Products/List')
part triggers a TypeScript error, stating:
Type error: Type 'Promise<typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'. Property 'default' is missing in type 'typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")' but required in type '{ default: ComponentType<any>; }'.
I am not quite sure what I am supposed to do here to get it to work.
If you'd rather use Create React App to initiate your project, you'll be pleased to know that CRA now supports TypeScript out of the box.
This is because the component will only be loaded when it is needed, and it will only be loaded once. So you should only use React. lazy when you need to load a component asynchronously. The component is not readily needed in the initial render of the app, and it is not needed in the render of a specific page.
It has been available for quite some time. In essence, lazy loading means that a component or a part of code must get loaded when it is required. It is also referred to as code splitting and data fetching . Talking about React specifically, it bundles the complete code and deploys all of it at the same time.
const OtherComponent = React.lazy(() => import('./OtherComponent')); This will automatically load the bundle containing the OtherComponent when this component is first rendered. React.lazy takes a function that must call a dynamic import() .
You should do export default class {...}
from the ./screens/Products/list
instead of export class ScreensProductList {...}
.
Or, alternatively, you can do:
const ScreensProductList = lazy(() => import('./screens/Products/List') .then(({ ScreensProductList }) => ({ default: ScreensProductList })), );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With