Code splitting in React

What is code splitting and how to introduce code splitting in React applications

In terms of bundle size, modern JavaScript applications can be very large. You don't want your users to download the 1MB JavaScript package (your code and libraries) just by downloading the first page, right? But this is by default, when you publish a modern web application built with Webpack bundling.

The bundle will contain code that may never run because the user will only stay on the login page and not see the rest of the application.

Code splitting is a practice of loading the required JavaScript only when needed.

This can improve:

  • The performance of your application
  • Impact on memory and battery usage on mobile devices
  • The kilobyte (or megabyte) size of the download

React 16.6.0, released in October 2018, introduced a method to perform code splitting, which should replace every tool or library previously used:React.lazywithsuspense.

React.lazywithSuspenseThe perfect way to form a lazy-loaded dependency and load it only when needed.

let us beginReact.lazy. You can use it to import any component:

import React from 'react'

const TodoList = React.lazy(() => import(’./TodoList’))

export default () => { return ( <div> <TodoList /> </div> ) }

The TodoList component will be dynamically added to the output as soon as it is available. Webpack will create a separate package for it and will be responsible for loading it when necessary.

SuspenseIs a component that can be used to wrap any lazy-loaded component:

import React from 'react'

const TodoList = React.lazy(() => import(’./TodoList’))

export default () => { return ( <div> <React.Suspense> <TodoList /> </React.Suspense> </div> ) }

It processes the output when getting and rendering lazily loaded components.

Use itfallbackProps output some JSX or component output:

...
      <React.Suspense fallback={<p>Please wait</p>}>
        <TodoList />
      </React.Suspense>
...

All of these can run normally on React Router:

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

const TodoList = React.lazy(() => import(’./routes/TodoList’)) const NewTodo = React.lazy(() => import(’./routes/NewTodo’))

const App = () => ( <Router> <React.Suspense fallback={<p>Please wait</p>}> <Switch> <Route exact path="/" component={TodoList} /> <Route path="/new" component={NewTodo} /> </Switch> </React.Suspense> </Router> )

Download mine for freeResponse Handbook


More response tutorials: