A picture of a rocket, a React logo, and a CopyCat logo.

Reactjs Build Production: Optimize Performance with a Deployment Build

February 25, 2022
Harita Ravindranath
React Best Practices

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Introduction to Reactjs Build Production

For running your React.js project, there are two modes are available – development and Reactjs build production. 

During the development phase, we will be running our code locally using the development mode where React provides us with many helpful warnings and tools for easily detecting and fixing problems in our application code and eliminating potential bugs. However, these extra codes increase bundle size and hence, a slower running app. 

While working on the app locally, this slowdown may be acceptable. But during deployment, this is not something we can afford. According to a Google study, 53% of users will leave a site if it takes more than 3 seconds to load. Consequently, we need to speed up our application at all costs, and this is where the production mode comes into the picture. You can also speed up development with CopyCat, a Figma to React plugin tool that eliminates sprint delays and reduces development time.


Try the following design in a sandbox.


In this article, we will be taking a deep dive into the Reactjs build production, deployment, and additional tips on optimising your React app’s performance.

So, let’s start!

What is the Production mode in React.js?

Your react application should run on the development mode while being developed. The app should run in production mode once deployed and published. So, what exactly does the production mode do?

The production mode minifies your code, optimises assets, and produces lighter weight source maps. Also, the warning messages and other features present in development mode for debugging will be suppressed. As a result, the bundle size is drastically reduced and improves page load time. React recommends utilising the production mode while deploying the application.

The main advantages of production mode are:

  • Performance boost compared to Development mode
  • Represents the performance of your app on the end user’s device
  • Helps to catch bugs that only show up in production

How to create a Production build production for your React app?

In this section, let us learn how to create Reactjs build production for your application. Likewise, here is the step by step instructions below.

Step 1: Firstly, let us start: create a new React application.

Open the terminal. Create a new react application using CRA by giving the following command

npx create-react-app my-app

The project is now set up with default files and configurations.

Step 2: Then navigate to the project folder

cd my-app

The initial project folder structure looks like this.

Step 3: Now, let us customize our app by editing the default code. Go to the src/App.js file and I am making some changes in the pre-existing text.

import logo from './logo.svg';
import './App.css';
 
function App() {
  return (
    <div className="App">
         <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          I love React!
        </a>
      </header>
    </div>
  );
}
 
export default App;

Step 4: Run the application (development mode). Go to the terminal and make sure you are in the project root. Give the command

npm run start

The app starts running in the development mode and is served at http://localhost:3000/

Step 5: Now let us create the production build for our application.

Make sure you are in the root folder within the terminal and run the following command

npm run build

And that’s it! Our Reactjs build production is now ready!

The build directory containing the production build is created within the root project folder.

Step 6: Let us run the app in production mode. Run the following command to serve the build version in a static server. 

npm install -g serve
serve -s build

The app is now running in production mode! Go to http://localhost:3000/ (or the address mentioned)

How to tell if the React app is running in development mode or production mode?

We have learned how to run our app in both dev and prod modes. Often, you might need to check which mode the app is currently running. For this purpose, we can use the browser extension React Developer Tools. 

Step 1: Install the React Developer Tools extension to your browser.

Step 2: Check the extension icon’s background colour. Ensure yours react app is running, and the browser extension is active. 

If the icon’s background colour is red, the app is in development mode.

And if the icon’s background colour is black, the app is in production mode.

Analyzing the Reactjs build directory

Previously, we have seen that on running the build command npm run build, the build directory of your app will be created inside the project’s root folder. Furthermore, let us briefly analyze the files inside the build directory.

Firstly, inside the build directory we have the static folder. This build/static folder contains your CSS, JS and media files.

Notice that for files within the build/static folder, a unique hash is appended to the file name. This hash code is generated based on the contents of the file itself, i.e., if the contents of the file change in the next build, the hash code (hence, the filename) will also change.

Therefore, the hash will be useful for enabling long term caching techniques. For example, on page reloading, the hashing will prevent re-downloading of all the assets if the contents of your file haven’t changed.

Many .js files are generated and placed inside the build/static/js directory. These are called chunks

[number].[hash].chunk.js

Your application code within App.js will be placed inside the following file.

main.[hash].js

Additional ways of Reactjs build production

In the above demo, we used the npm run build command provided by the Create React App (CRA) for creating our production build. There are also other tools through which you can generate your prod build. Likewise, let us discuss a few of them in this section.

  1. Brunch

Brunch is a Fast front-end web app build tool useful for efficiently creating production build.

npm install -g brunch

For Reactjs build production, run the following command

brunch build --production
  1. Browserify

Browserify is an open-source JavaScript bundler using which you can also create a production build. For efficient build generation, install a few additional plugins.

npm install --save-dev envify terser uglifyify

For creating the build, run the following command

browserify ./index.js \
  -g [ envify --NODE_ENV production ] \
  -g uglifyify \
  | terser --compress --mangle > ./bundle.js
  1. Webpack

Webpack is one of the most popular choices when it comes to creating production build. If you are configuring webpack directly, make use of the TenserPlugin.

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  mode: 'production',
  optimization: {
    minimizer: [new TerserPlugin({ /* additional options here */ })],
  },
};
  1. Rollup

Rollup is another popular module bundler of JavaScript applications. 

npm install -- rollup

For an efficient build production using Rollup, few additional plugins are required.

npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser

Configure them as below

plugins: [
  // ...
  require('rollup-plugin-replace')({
    'process.env.NODE_ENV': JSON.stringify('production')
  }),
  require('rollup-plugin-commonjs')(),
  require('rollup-plugin-terser')(),
  // ...
]

Confused which of these bundlers is right for your project? Check out this blog which has compared all the major bundlers in detail.

https://medium.com/swlh/webpack-vs-rollup-vs-parcel-vs-browserify-bundle-size-build-time-ease-of-use-comparison-d80699822c37

How to deploy your React app?

Once the production build is ready, the next step is to deploy your React application for production. Specifically, to host our React application, numerous hosting providers are available. Few options to choose from are

  • AWS
  • Azure
  • Digital Ocean
  • Github Pages
  • Heroku
  • Netifly
  • Firebase
  • Vercel etc.

Subsequently, in this section, let us explore how to deploy our react application using a couple of these services.

  1. AWS S3 for Static Hosting

AWS S3 allows you to deploy your application statically. Many projects prefer static deployment because of two obvious benefits.

  • Ease – Only a few steps are required to set and maintain the app.
  • Cost – Since it is easy to set up and maintain, deployment costs are dramatically cheaper.

Follow the below instructions to achieve Reactjs build production for S3.

  1. Deploy to S3

Amazon Simple Storage Service (Amazon S3) is a service helpful in storing static assets. Further, you can store any form of static assets within an S3 bucket – images, files, and even your application’s static HTML, CSS, and JS files. For deploying your app to S3, follow the steps below. 

Step 1: First, create an account or sign in to the AWS 

https://aws.amazon.com/

Step 2: Go to S3 services and click on “Create bucket”

Step 3: Configure the bucket. 

Give a unique name for your bucket.

Also, disable the “Block all public access” settings so that your live app will be visible to the public. 

With basic configurations now done, proceed to create the bucket.

Step 4: Set properties.

 Open the newly created bucket. Select the “Properties” tab and go to “Static website hosting”. Enable static web hosting.

Fill in  index.html for both Index document and Error document fields. Save changes.

Step 5: Set permissions.

Go to the “Permissions” tab and select “Bucket Policy”. You can fill in the policies here. As a starter, let us set read-only access to anonymous users. Make sure you mention your app details for the “Resource” field. Save Changes.

Step 6: Now, upload your production build to the S3 bucket.

Click on “Upload” and select the build directory from your machine. That’s it!

Find the hosted URL of your website under “Static Website Hosting” within the “Properties” tab.

Congratulations! Your app is now live!

Bonus: Deploying with AWS CLI

Alternately, you can also manage your S3 bucket via the AWS CLI. 

Step 1: Install AWS CLI 

aws configure

Step 2: Open the CLI and configure it by running 

Provide your details.

AWS Access Key ID [None]: YOUR_ACCESSKEY_ID
AWS Secret Access Key [None]: YOUR_ACCESSKEY
Default region name [None]: us-west-2
Default output format [None]: json

Step 3: Check that your bucket is available by listing. You can also create if not already created.

// create a bucket
$ aws s3 mb s3://your-bucket-name

// list buckets
$ aws s3 ls

Step 4: To build and deploy your app, run

// build and deploy the app
$ npm run build && aws s3 sync build/ s3://your-bucket-name

The existing contents of the bucket will be replaced by the latest contents of the build directory, generated by running npm run build.

Check out the official documentation to find more handy CLI commands

https://docs.aws.amazon.com/cli/latest/userguide/cli-services-s3-commands.html

Notes:

  • Use AWS IAM for creating a user with security credentials
  • You can make use of AWS CloudFront – a CDN service offered by AWS which can further optimize your app making it highly available globally.

If you wish to learn more about Static Hosting your React app with AWS S3 and Cloudfront, you might find this video useful.

  1. Netlify for Continous Delivery

Netlify helps us to build and host high performance React apps. Let us learn how.

Step 1: Sign up to Netlify. Create an account.

Step 2: Start a new project by clicking ‘Add new site

Step 3: Netlify provides you three options to host your app

Similarly, you may deploy manually by uploading your build file. For this demo, let us try hosting our site by connecting with our Git repository to set up continuous delivery.

Note: Your app should be hosted in a Git repository

Step 4: Pick your repository

Step 5: Deploy your site.

Your site is now available at the custom URL!

To learn more about Reactjs app deployment for production, check out this insightful video.

Tips: Optimizing the Performance of your React app

Particularly, using the minified production build for deployment can boost the performance of your React application. In this section, let us also discuss some additional ways to speed up your application.

  1. Virtualize Long Lists

If your application contains super large tables or lists (containing hundreds or thousands of rows), it can immensely slow down your site’s performance.  Hence to avoid this, make use of Virtualization

Popular libraries that support virtualization for rendering large lists efficiently are

In particular, this blog will help you get started with React-window in your application.

https://web.dev/virtualize-long-lists-react-window/

  1. Avoid Reconciliation

The virtual DOM in react supports reconciliation. Every time there is a change in the component, it gets re-rendered. The re-rendering takes some time, and in most cases, this is not a problem. However, if the slowdown is noticeable in your application, you can speed this up by skipping the whole re-rendering process.

Update the shouldComponentUpdate lifecycle function, which gets called before every component re-render, by returning a false value.

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

Thus, make use of this in situations where you know you don’t need to re-render your component on every update. You may also make use of React.PureComponent.

  1.  Code-splitting and Lazy Loading

Another important optimisation technique for a React app is Code Splitting. The default “bundle” of the React application contains the entire application code, which will be loaded and served to the user once when the application is rendering in the browser. However, as the app grows, the file size increases and the bundle size increases. And at some point, the initial page load starts slowing down. For overcoming this situation, Code splitting can come in handy.

How to Code Split

React allows you to split your large bundle file into multiple smaller chunks using Code splitting. And these chunks are dynamically imported using import()  and then loaded on-demand using React.lazy. This strategy allows you to drastically improve the app performance by bringing down initial load time.

Step 1: Transform the normal React imports to dynamic imports.

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

Step 2: Add Suspense and fallback mechanism

<React.Suspense fallback={<p>Loading page...</p>}>  <Route path="/" exact>    <Home />  </Route>  <Route path="/about">    <About />  </Route></React.Suspense>

Conclusion

Overall, the production build helps you improve your application’s performance by bringing down the bundle size. Moreover, It is useful for testing how our application performs in the end user’s device and hence prevent a buggy experience. In this tutorial, we explored Reactjs build production and how to deploy our app for production. Additionally, we discussed strategies to further optimize your React application’s performance. Hoping this article turned out to be beneficial!

Happy Coding!

Interesting Reads From Our Blog

Related Articles

  • React Best Practices

    React SVG: How to use SVGs best in React

    In this article, we’ll look at the SVG image format, how to import SaVG in react, how to convert SVG to react components and the benefits and drawbacks of using SVGs in react. What is an SVG? SVG is a…

    April 1, 2022
  • React Best Practices

    How React.js CDN Makes Your Life Incredibly Easier

    Introduction Setting up a React Project sometimes comes with time-consuming steps, especially when you are a beginner to the React ecosystem. You need to worry about npx, create-react-app, accurate npm version, React associated libraries, etc. However, ReactJs CDN makes your…

    April 1, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code