OneCompiler

Code Splitting in react using react router

368


In this post, we are going to see how we can reduce our React app startup time using code splitting.

What is Code Splitting?

It is the process of splitting the code into parts in which the components will load dynamically instead of a single JS Bundle.

Code without Code Splitting

consider we have a code like below in App.js

import React from "react";
import Nav from "./components/nav";
import Home from "./components/Home";
import Content from "./components/Content";
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'

const App = () => {
    return (
        <Router>
            <Nav />
            <Switch>
                <Route exact path="/" component={Home} />
                <Route  path="/contents" component={Content} />
            </Switch>
        </Router>
    );
};

export default App;

when we run our react app, react will make a bundle file that stores the entire code in a single file called bundle.js. Our app load time depends on this file size. To reduce the size we use code splitting. If we don't use code-splitting, all components that we imported will all load at once.

Code with Code Splitting

import React from "react";
import Nav from "./components/nav";
const Home = React.lazy(()=> import('./components/Home'))
const Content = React.lazy(()=> import('./components/Content'))
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'

const App = () => {
    return (
        <Router>
          <React.Suspense fallback={<h1>loading</h1>} >
            <Nav />
            <Switch>
                <Route exact path="/" component={Home} />
                <Route  path="/contents" component={Content} />
            </Switch>
         </React.Suspense>
        </Router>
    );
};

export default App;

Only when we go to a specific route, The corresponding component will load dynamically.