How Can We Achieve Code Spliting in React Js?

Introduction

In modern web development, making your application fast and easy to use is very important. One way to do this is through code splitting. In React, code splitting helps by loading only the code needed for the first page view and waiting to load other parts until they are needed. This makes the initial load time shorter and improves the user experience, especially for large applications.

What is Code Splitting?

Code splitting is a method that breaks your code into smaller bundles that can be loaded when needed. Instead of loading the entire application at once, you only load the necessary parts. This makes your application faster and more efficient.

Why Use Code Splitting?

  • Improved Performance: Loads only the necessary code, reducing initial load time and making the app feel faster.
  • Better User Experience: Users enjoy quicker load times and smoother interactions.
  • Efficient Resource Use: Minimizes the amount of JavaScript that needs to be processed at startup.

How to Implement Code Splitting in React

There are several ways to do code splitting in React. The most common methods are using import() dynamically and React's React.lazy and Suspense components.

Using Dynamic import()

The import() function lets you load JavaScript modules dynamically. It returns a promise that resolves to the module once it’s loaded.

// Without code splitting
import Component from './Component';

// With code splitting
const Component = React.lazy(() => import('./Component'));

Using React.lazy and Suspense

React provides React.lazy and Suspense to load components only when needed. React.lazy uses a function that calls import() and returns a promise that loads a React component.

Example

import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}
export default App;

In this example, LazyComponent loads only when needed. The Suspense component needs a fallback prop, which shows a React element while the lazy-loaded component is loading.

Code Splitting with React Router

React Router supports code splitting by loading routes lazily, so only the code for the current route is loaded.

Example

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
        </Switch>
      </Suspense>
    </Router>
  );
}
export default App;

In this example, the Home and About components load only when their routes are accessed.

Advanced Code Splitting with Webpack

For more advanced cases, you can use Webpack's built-in support for dynamic imports and code splitting. Webpack can automatically split code based on your settings and create separate bundles.

Example Webpack Configuration

module.exports = {
  entry: './src/index.js',
  output: {
    filename: '[name].bundle.js',
    path: __dirname + '/dist',
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
};

This setup instructs Webpack to divide imported modules into smaller pieces, which can make the application faster by creating smaller bundles.

Summary

Code splitting is a powerful method to make React apps faster and improve user experience. By loading only what's needed right away and delaying the rest, you can greatly cut down on initial loading times and build more efficient applications. Whether you're using React.lazy and Suspense, integrating with React Router, or using advanced Webpack setups, code splitting is crucial for optimizing React development.