React Training
  • React JS Library
  • Roadmap
  • Training OutLine
  • React js basics
    • Understanding React JS
    • React JS a framework?
    • Setting Up React
    • Say Hello to React
    • Everything is a Component
    • Create-react-app
  • React Building Blocks
    • JSX and Babel
    • One Way Data Flow
    • Virtual DOM
    • V of MVC
    • React Terminology
    • React Tooling
  • Day 01
    • Day 01 OutLine
    • All About JSX
    • React Tools/ npm & webpack
    • Introduction of Webpack
    • Hello world using webpack
      • Webpack Setting up with React
    • NPM Scripts | Package JSON
      • Package.json file
    • React JS Principles
      • One Way Data Flow
      • V of MVC
      • Virtual DOM
    • Create React App - Part-1
    • Create React App - Part-2
  • Day 02
    • Quick Recap
      • Quiz
    • State & Props
      • State & Props in Depth
      • State Vs Props | Compare
    • React LifeCycle Methods
      • React LifeCycle Methods for V-0.16 x
    • Constructor | Lifecycle
    • Write Flicker App | First App
  • Day 03
    • Quick Recap
    • Life Cycle Flow
      • Birth and Mounting
      • Initlization and Construction
      • Pre Mounting
      • Render Method
      • componentDidMount
    • Type of React Components
      • Examples- Quick Compare
      • Class and Functional components
      • Functional Components
    • YouTube application
      • Component Design
    • All in One LifeCycle
  • Assignment
    • React App development
  • Day 04
    • Quick Recap on Lifecycle
    • Lifecycle deprecated/New Methods
      • New Lifecycle Methods
    • Lets Build App Netflix | Mock
  • Assignment
    • Github battle App | Assignment
  • Day 05
    • Quick Recap : Hooks
    • ES6 Features | Hands-on
      • ES6 Code Examples
    • Next Stop - React Router | SPA
      • Code examples | Router
      • React Router Building Blocks
      • Application using react-router-dom
  • Day 06
    • Router V4 | Quick Recap
    • ES2015 | 16 Quick Recap
    • LifeCycle Methods -Part-1
    • LifeCycle Methods -Part-2
  • Day 07
    • Quick Recap | New Lifecycle
    • Quick Recap | React Routing
    • Context API | React JS
      • component with context APIs
      • Context API | examples
    • App using Hooks/Context APIs
  • Assignment
    • Assignments
  • State Management Day-08
    • Quick Recap
    • Managing React State
      • What is Redux
      • Understanding Redux
      • Hello World "Redux"
  • React Redux Day - 09
    • Redux State Manager
    • Redux Redux Development
    • Simple Application | Redux
  • Redux Live Application Day -10
    • Redux with existing Application
      • Redux with React App
      • Lets Build More Apps
      • Should I use Redux from Dan
    • Quick Look at JS in React
    • Learn By Reading
  • miscellaneous Items - Day 11
    • Hooks useReducer
    • Hooks useContext
    • Hooks useRef
    • Hooks useEffect
    • Hooks useState
    • Lazy Loading and code splitting
    • Styling React Component
  • React Next Step - Day 12
    • Topics
    • Jest and Enjyme Testing
    • Examples: Testing
  • React Native
    • What is React Native
    • Setting up Environment
      • Linux Systems
    • React Native Hello World App
    • React Native Architecture
    • React Native Vs Native
    • Expo Cli or React Native CLI
  • React Native core Fundamental
    • React Native "Hello World"
    • Course OutLine
    • Getting started with Expo App
    • Layout with Flexbox
    • Working with Styles and Events
    • Manging Component State and Props
    • Build Simple Task List Application
  • What to Debug & How to Debug
    • Debug React Native Application
Powered by GitBook
On this page

Was this helpful?

  1. miscellaneous Items - Day 11

Lazy Loading and code splitting

PreviousHooks useStateNextStyling React Component

Last updated 5 years ago

Was this helpful?

The new release of React 16.6 rolled in with some new features that can be used to add more power to React components with little amounts of effort.

Two of these new features are React.Suspense and React.lazy(), which make it very easy to apply code-splitting and lazy-loading to React components.

This article focuses on how these two new features can be used in React applications and the new potentials they open up to React developers.

Code-splitting

Writing JavaScript applications has evolved over the last few years. With the advent of ES6(modules), transpilers like , and bundlers like and , JavaScript applications can now be written in a completely modular pattern for easy maintainability.

Usually, each module gets imported and merged into a single file called the bundle, and then the bundle is included on a webpage to load the entire app. However, as the app grows, the bundle size starts becoming too large and hence begins to impact page load times.

Bundlers like Webpack and Browserify provide support for code-splitting, which involves splitting the code into different bundles which can be loaded on demand (lazy-loaded) instead of being loaded all at once, thereby improving the performance of the app.

Dynamic Imports

One of the major ways of splitting code is using dynamic imports. Dynamic imports leverage on the import() syntax, which is not yet part of the JavaScript language standard but is still a proposal that is expected to be accepted soon.

Calling import() to load a module relies on JavaScript Promises. Hence, it returns a promise that is fulfilled with the loaded module or rejected if the module could not be loaded.

For older browsers, a polyfill like should be used to shim Promise.

Here is what it looks like to dynamically import a module for an app bundled with Webpack:

When Webpack sees this syntax, it knows to dynamically create a separate bundle file for the moment library.

Code-splitting React components

Several techniques have been in use for code-splitting React components. A common approach is applying dynamic import() to lazy-load Route components for an application — this is usually referred to as route-based code-splitting.

Consider the following React component called MyComponent:

Here, the OtherComponent is not required until MyComponent is getting rendered. However, because we are importing OtherComponent statically, it gets bundled together with MyComponent.

We can use react-loadable to defer loading OtherComponent until when we are rendering MyComponent, thereby splitting the code into separate bundles. Here is the OtherComponent lazy-loaded using react-loadable.

Here, you see that the component is imported using the dynamic import()syntax and assigned to the loader property in the options object.

React-loadable also uses a loading property to specify a fallback component that will be rendered while waiting for the actual component to load.

Using Suspense and React.lazy()

In React 16.6, support for component-based code-splitting and lazy-loading has been added via React.lazy() and React.Suspense.

React.lazy() and Suspense are not yet available for server-side rendering. For server-side code-splitting, React Loadable should still be used.

React.lazy()

React.lazy() makes it easy to create components that are loaded using dynamic import() but are rendered like regular components. This will automatically cause the bundle containing the component to be loaded when the component is rendered.

React.lazy() takes a function as its argument that must return a promise by calling import() to load the component. The returned Promise resolves to a module with a default export containing the React component.

Suspense

A component created using React.lazy() only gets loaded when it needs to be rendered.

Hence, there is need to display some form of placeholder content while the lazy component is being loaded — possibly a loading indicator. This is exactly what React.Suspense was created for.

React.Suspense is a component that is meant for wrapping lazy components. You can wrap multiple lazy components at different hierarchy levels with a single Suspense component.

The Suspense component takes a fallback prop that accepts the React elements you want rendered as placeholder content while all the lazy components get loaded.

An error boundary can be placed anywhere above lazy components to show nice user experience if a lazy component fails to load.

I have created a very simple demo on CodeSandbox to demonstrate using React.lazy() and Suspense for lazy-loading components. example on same is available here

For React apps, code-splitting using dynamic import() happens on the fly if boilerplates like or is being used.

However, if a custom Webpack setup is being used, then you need to check the for setting up code-splitting. For Babel transpiling, you also need the plugin, to allow Babel parse dynamic import() correctly.

However, there is a very popular package for code-splitting React components called . It provides a higher-order component (HOC) for loading React components with promises, leveraging on the dynamic import() syntax.

You can learn more about what you can accomplish with react-loadable in this .

create-react-app
Next.js
Webpack guide
babel-plugin-syntax-dynamic-import
react-loadable
documentation
Babel
Webpack
Browserify
es6-promise