What is ReactJS Code Splitting? How Does React Code Splitting Work?
Understanding Code Splitting
What is ReactJS Code Splitting?
Code splitting allows programmers to omit certain dependencies from bundles and insert them only where they are needed. This means that these dependencies are loaded only when needed. Result? The page loads quickly.
While the page is still loading the same amount of code, it may not execute all the loaded code. This results in a difference in page loading speed. Consider, for instance, if a dynamic element in a page requires a large dependency, it could cause a significant page lag.
Now, if the dependency is loaded only when the element is used, no lag will be generated.
Bundlers like Webpack, Rollup, and Browserify support the code-splitting feature.
How Does Code Splitting Work in ReactJS?
You can implement code-splitting in React in several ways. Some of them are listed here.
The simplest way to split a code is to import a module dynamically. There can be times when you may not need to import a module. Websites can dynamically import elements based on user actions.
Here's an example of how to dynamically load a module when the user clicks an element.
React.lazy makes it easy to code-split a React application on a component level using dynamic imports. It allows you to import a dependency dynamically and render that dependency as a component in a single line of code.
React.lazy with Suspense
However, even when you use React.lazy, there will always be a slight delay while the code-split component is being fetched over the network. This can affect user experience. Therefore, it is crucial to display a useful loading state. React.lazy with the Suspense component can help solve this problem.
Test your knowledge with a quick quiz!
What is used when there's a slight delay while fetching data in ReactJS?
Select the correct answer
How Suspense works?
It accepts a fallback component and allows you to display any React component as a loading state. Let us understand this through an example.