DEV Community

Cover image for Performance Tips Every JS React Developer Should Know.
Kartik Budhraja
Kartik Budhraja

Posted on

Performance Tips Every JS React Developer Should Know.

Introduction

Building a React app is easy. But optimization is the most difficult part. As a Javascript React developer, consistently improving the performance of your applications is an essential skill to master.

Code Splitting :

Code Splitting is one of the most popular techniques for optimizing web performance. In Code Splitting, we split our application into smaller chunks and load them when needed. and lazy() will help us with this.

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

const Parent = () => {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Use PureComponent and React.memo for Component Optimization :

To avoid unnecessary re-renders, we can use PureComponent and React.memo.

PureComponent is a class component that implements the shouldComponentUpdate lifecycle method to perform a shallow comparison of its props and state. If the props and state have not changed, the component will not update. This can significantly improve application performance, especially for large and complex components.

React.memo is a higher-order component that works similarly to PureComponent, but for function components. It performs a shallow comparison of the component's props and returns a memoized version of the component if the props have not changed. This can also improve application performance, especially for functional components that rely on props.

Production Builds :

Ensure your Webpack configuration is set to production mode to enable optimizations like code minification and dead code elimination.

// webpack.config.js
module.exports = {
  mode: 'production',
  // other configurations...
};
Enter fullscreen mode Exit fullscreen mode

Virtualization :

When dealing with large data sets, rendering all the data at once can lead to slower application performance. To avoid this, you can use virtualization to render only the visible data and load more data as the user scrolls.

Virtualization can be achieved using third-party libraries like react-window or react-virtualized. These libraries provide a way to render only the visible data and load more data as needed, resulting in faster application performance.

import { FixedSizeList } from 'react-window';
function VirtualizedList() {
  return (
    <FixedSizeList
      height={400}
      itemCount={1000}
      itemSize={40}
      width={300}
    >
      {({ index, style }) => (
        <div style={style}>Item {index}</div>
      )}
    </FixedSizeList>
  );
}

Enter fullscreen mode Exit fullscreen mode

Optimize Images :

Images can become an enemy of web performance. So, we need to use images in the React project cautiously. We can use techniques like Lazy Loading Images, Image Compression, and Right Image Formatting to optimize images in the project.

<img src="placeholder.jpg" loading="lazy" alt="Lazy Loaded Image" />
Enter fullscreen mode Exit fullscreen mode

Server-Side Rendering (SSR) :

Consider server-side rendering (e.g., with Next.js) to render React components on the server, improving initial load times and SEO.

// pages/index.js
import React from 'react';const HomePage = () => {
  return (
    <div>
      <h1>Hello, Next.js SSR!</h1>
    </div>
  );
};
export default HomePage;
Enter fullscreen mode Exit fullscreen mode

Caching :

Caching is one of the most underrated ways to improve performance. Implement client-side caching for data that doesn't change frequently to reduce the need for unnecessary API calls.

Use Web Workers for Expensive Computation :

Expensive computation can also lead to slower application performance. To avoid this, you can use Web Workers to perform expensive computation in the background, freeing up the main thread for rendering and other tasks.

Web Workers are a way to run JavaScript code in a separate thread, allowing for parallel execution of code. You can use Web Workers to perform expensive computation like sorting or filtering data, without blocking the main thread and slowing down the application.

// worker.js
onmessage = function (e) {
  const result = performHeavyCalculation(e.data);
  postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function (e) {
  console.log('Result:', e.data);
};
worker.postMessage({ /* data for calculation */ });
Enter fullscreen mode Exit fullscreen mode

Bundle Analysis :

Regularly analyze your bundle size using tools like Webpack Bundle Analyzer. Identify and eliminate unnecessary dependencies.

# Install the analyzer package
npm install --save-dev webpack-bundle-analyzer# Update npm scripts
"scripts": {
  "analyze": "webpack --profile --json > stats.json && webpack-bundle-analyzer stats.json"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, I have discussed some of the most popular techniques for improving React Performance.

Follow Me on Social Media!

If you found this article helpful, feel free to connect with me on LinkedIn and Twitter for more programming tips and tutorials. Let's learn and grow together!

LinkedIn: https://www.linkedin.com/in/kartikbudhraja/

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.