Signup/Sign In

Tips to Improve Performance of your React JS Application

Posted in Technology   NOVEMBER 30, 2023

    If you are working on a React JS project at work, and you are assigned the task of improving the performance of the application or suggesting code improvements to improve the performance of the ReactJS application, then read this article till the end, and take away some very useful performance improvement tips for React JS that only senior developers know. Wait! Are you a Senior Developer?

    This article will guide you to supercharge your React JS knowledge and learn how you can build ReactJS applications that will perform well.

    The tips listed below are the best optimizations that you can do to improve the performance, speed, responsiveness, and loading time of your ReactJS application. So get ready to learn ReactJS performance improvement techniques.

    1. Use Functional Components instead of Class components

    Functional components are faster than Class components. So if you have any legacy code using class component, you can plan to move it to functional component implementation. Here's an example of a functional component:

    import React, { useState } from 'react';
    
    function MyCounterApp() {
      const [count, setCount] = useState(0);
    
      const increment = () => {
        setCount(count + 1);
      };
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={increment}>Increment</button>
        </div>
      );
    }

    Also, wherever possible try using React hooks, as they will surely improve the performance of your application. If you use react hooks properly you can avoid unnecessary re-renders of components.

    2. Use 'key' props while using Lists

    When you use a list of values and display them on UI in your JSX code, you will see a warning regarding the unique key prop for each item.

    It is good practice to assign each list item a unique key when it is used to create some UI. When each list item has a unique ley prop then React can figure out which list item go change and update just that while updating the user interface.

    Here's an example:

    import React from 'react';
    
    function MyListUI(){
      let items = [1,2,3,4,5]
      return (
        <div>
            {items.map((index, val) => (
                <div key={index}> {val} </div>
            ))}
        </div>
      );
    }

    3. Pagination or on-scroll loading of Long lists

    If you have to display a long list of data, either use pagination or go with dynamic loading on-scroll. To implement this, you can use react-window or react-virtualized library. Using this library you can ensure that only the visible items will be loaded, and the rest of the list items will be loaded when the user scrolls and they are in the visible area.

    Imagine loading only 10 list items out of 10,000 initially, and then as the user scrolls down, the next 10 get added to the list, and then the next 10, and so on.

    4. Lazy Loading

    You can split the code of your components and use lazy loading to reduce the size of your bundle and also improve the performance.

    In the case of Lazy loading, only the required components are loaded initially, and then as the user interacts with your application, the JS for components are loaded if they are required.

    React comes with React.lazy function to load components dynamically, when required.

    Here's a code example,

    import React, { lazy, Suspense } from 'react';
    
    const LazyComponent = lazy(() => import('./LazyComponent'));
    
    function MyComponent() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent />
        </Suspense>
      );
    }

    5. Use Web Workers

    If you have some code that is supposed to perform some computational task then you can use Web workers so that your ReactJs application doesn't hang. If the computationally intensive task is running on the main thread, then your application will not respond to user interaction.

    Hence, using Web Worker is a great way to take off load from the main worker thread. In a way, this can be used to implement parallel execution of tasks.

    // worker js
    self.onmessage = (e) => {
      const result = someComplexCalculation(e.data);
      self.postMessage(result);
    };
    
    // component js
    const App = () => {
      const [result, setResult] = useState(null);
    
      const calculateFibonacci = (num) => {
        // Create a new Web Worker
        const worker = new Worker();
    
        // Handle messages from the worker
        worker.onmessage = (e) => {
          setResult(e.data);
    
          // Terminate the worker after the task is done
          worker.terminate();
        };
    
        // Start the worker and pass data
        worker.postMessage(num);
    };

    6. Using useMemo Hook

    If you have some complex calculations or computations done as part of some function execution, then you can use the useMemo hook of ReactJS, so that the results are memorized. Using the useMemo hook, you can associate a function with some data point, and if the data changes then only recalculations are performed.

    Here is a code example:

    const ExampleComponent = () => {
      // State variables
      const [count, setCount] = useState(0);
    
      // Expensive computation function
      const expensiveComputation = (value) => {
        console.log('Performing expensive computation...');
        // Simulating an expensive computation by squaring the input value
        return value ** 2;
      };
    
      // Memoized result using useMemo
      const memoizedResult = useMemo(() => {
        return expensiveComputation(count);
      }, [count]); // Recompute the result only if the 'count' dependency changes
    
      return (
        <div>
          <h2>useMemo Example</h2>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment Count</button>
          <p>Memoized Result: {memoizedResult}</p>
        </div>
      );
    };
    

    7. Using React.memo

    You can also use React.memo to memoize functional components in order to prevent re-rendering of components again and again.

    With memo, we can make sure that the component is not re-render unless its props change. Yes, even if the parent component re-renders then also your child component will not be re-rendered if there is no change in the props value.

    Here is a code example, where we have used memo,

    const Greeting = memo(function Greeting({ name }) {
      return <h1>Hello, {name}!</h1>;
    });
    
    export default Greeting;

    8. Memoization with Libraries

    There are some 3rd party libraries also that can be used to leverage memorization for expensive functional calls.

    You should explore memoize-one and reselect, in order to cache the results of function calls that you don't want to execute again and again if there is no change in the supplied data.

    9. External CSS

    You must avoid internal CSS directly in your JSX code. Always use external CSS so that you can utilize the benefits of caching and browser cache.

    You should also see how you can optimize your CSS file. Re-use styling, minify the CSS file, you can even break down one CSS into smaller pieces and manage the delivery of the CSS files.

    10. Performance Profiling

    You can also use profiling tools like React DevTools Profiler, or Chrome Devtools, etc. See how much time your API calls are taking, component loading and re-loading, etc.

    Conclusion

    So these were some simple yet effective techniques that you can use in your ReactJS application to improve the overall code of the application and optimize the performance of the application too. If you want to learn ReactJS from the start, you should check out our FREE YouTube playlist for ReactJS tutorial.

    Keep learning, Keep growing!

    Author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    web-developmentreactjs
    IF YOU LIKE IT, THEN SHARE IT

    RELATED POSTS