How do React.lazy and code splitting work?
The React.lazy function, together with the code splitting mechanism, solves one of the main problems of large client-side applications—reducing the initial page load time. If a user visits the main page of a site, they absolutely do not need to download the JavaScript code of the admin panel or heavy modal windows that may not even be needed during the entire session. Code splitting allows cutting the final bundle into small logical parts and delivering them to the browser strictly on demand.
To implement this approach, the component is wrapped in a call to React.lazy, which accepts a function with a dynamic import. Since this import is asynchronous, React encounters a wait state during rendering and requires a parent element with a fallback state to be present. Thus, React.lazy is inextricably linked with the Suspense component, which displays a loading indicator at the moment the required module is downloaded from the network.
Proper design of code splitting points requires balance. Most of the time, code is split by pages or major application routes using a router. Less frequently, isolated heavy widgets, charts, or code editors that open upon a direct user click are split. At the same time, you should not break the application into too small parts, as this will lead to a snowballing growth of HTTP requests for small files, which will degrade overall network performance.
To control the size and structure of the resulting chunks, developers use special build analysis tools. Bundle analyzers visually show which libraries and modules take up the most space in the final files. This helps to timely detect code duplication or the accidental inclusion of heavy dependencies in the initial bundle of the application.
Recommendations for using React.lazy and code splitting: