Introduction
Performance is a key factor when building large-scale React applications. Users expect applications to load quickly, be responsive, and provide a smooth experience. Effective techniques for achieving these goals are code partitioning and lazy loading.
In this blog, we’ll explore what code partitioning and lazy loading are, how they work in React, and how you can use them to optimize your React app.
What is Code Splitting?
Code splitting is the practice of dividing your JavaScript code into smaller parts. To be able to load all applications as required, Instead of loading it all at once. This technique reduces initial load times by loading only the code required to render the current view by postponing the loading of other parts of the app until needed.
React provides an easy way to implement code separation using dynamic imports.
Benefits of Code Splitting
Faster initial load: Instead of downloading the entire app’s code upfront, only necessary code will be loaded initially. This will make the page load faster.
Improved user experience: Parts of the app can be loaded as needed. Make the app feel more responsive.
Reduced bundle size: A smaller JavaScript bundle results in a smaller download size for users.
What is Lazy Loading?
Lazy loading is a technique in which resources such as images, components, or other content are loaded only when actually required or visible to the user. In the case of React, lazy loading means dynamically loading a React component when it is about to be loaded, rendered, and not loaded with the default JavaScript package.
React has a built-in function called React.lazy() which allows component-level lazy loading.
Benefits of Lazy Loading
Reduces Initial Load Time: Only the components that are required to display the initial view are loaded, and others are loaded on demand.
Better Resource Management: Resources are loaded only when necessary, reducing the load on the user’s device.
How Code Splitting and Lazy Loading Work in React
React uses dynamic imports and React.lazy() to partition code and do lazy loading. Let’s take a step-by-step look at these tips and how to use them in your React application.
1. Code Splitting with React.lazy() and Suspense
React.lazy() allows you to dynamically import components. By wrapping a component in React.lazy(), React separates that component into separate pieces that are loaded only when needed.
Here’s how to use React.lazy():
import React, { Suspense } from 'react';
// Lazy load the component
const MyComponent = React.lazy(() => import('./MyComponent'));
const App = () => {
return (
<div>
<h1>Welcome to My App</h1>
{/* Suspense will show a fallback (loading spinner) while the component is loading */}
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
};
export default App;
How it Works:
React.lazy(() => import('./MyComponent')): This tells React to load MyComponent only when it’s required (i.e., when the component is rendered).
Suspense: This is a React component that wraps the lazily-loaded component. It displays a fallback UI (such as a loading spinner) while the component is being loaded.
2. Code Splitting with React Router
When building a single page application (SPA), you often want to partition your code. React Router provides an ideal scenario for using code partitioning with Lazy Load.
For example, consider a multipath React app. Each path can lazily load its associated components.
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// Lazy load route components
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));
const Contact = React.lazy(() => import('./Contact'));
const App = () => {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Suspense>
</Router>
);
};
export default App;
3. Dynamic Imports for Non-Component Assets
Apart from React components, you can also use dynamic imports to load non-JavaScript resources like styles or JSON files only when needed.
const loadCSS = () => import('./styles.css');
const App = () => {
const loadStyles = () => {
loadCSS().then(() => {
console.log('CSS loaded');
});
};
return (
<div>
<h1>Lazy Loading CSS</h1>
<button onClick={loadStyles}>Load Styles</button>
</div>
);
};
export default App;
Conclusion
Optimizing React applications using code partitioning and lazy loading is essential to improving performance. Especially as your application becomes more complex. By reducing the initial load time you can ensure that users can quickly interact with your app and provide a better experience. Code splitting and Lazy loading when used together, these techniques can greatly improve the performance of your React app. This results in faster loading and a more responsive user experience. Try using it in your project today to see the difference!
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency