Approach to implement Code Splitting
- React.lazy(): In the `App.js` file, we use `React.lazy()` to lazily load the `LazyComponent`. The `import()` function is passed as an argument to `React.lazy()`, which dynamically imports the component. It returns a `Promise` for the module containing the component.
- Suspense: We wrap the `<LazyComponent />` with the `<Suspense>` component. Suspense allows us to specify a loading indicator (fallback) while the lazily loaded component is being fetched. In this example, we display a simple “Loading…” message as the fallback.
- Asynchronous Loading: When the `App` component mounts, React starts fetching the code for `LazyComponent` asynchronously. While the component is being loaded, the `Suspense` component displays the loading indicator.
- Rendering LazyComponent: Once the code for `LazyComponent` is fetched and loaded, React renders the `LazyComponent` in place of the `<Suspense>` component.
How to Implement Code Splitting in React ?
In this article, we will learn about Implementing React code splitting via React.lazy() and Suspense improves app performance by loading code asynchronously and on-demand.
Contact Us