React & JavaScript Optimization Techniqu ...

React & JavaScript Optimization Techniques

Jan 26, 2024

When we begin a project, we tend to focus on things like scalability, usability, availability, security, and others. But, as the application grows, we may observe a decline in its speed and performance. It is often only at this point that we recognize the need for optimization.

In this article, we will present some of the most common techniques for optimizing code, which can be implemented in any application; we will also show optimization techniques using sample code written in JavaScript (https://developer.mozilla.org/en-US/docs/Web/JavaScript) and React.(https://react.dev/) The following techniques are gonna be covered:

  • Debouncing

  • Throttling

  • Memorization

  • Pure Components

  • Lazy Loading

  • Virtualization (or Windowing)

  • Error Boundaries

  • Inline Functions

1. Debouncing

Debouncing is a programming technique used to optimize the processing of functions that consume a lot of execution time. This technique involves preventing those functions from executing repeatedly without control, which helps improve the performance of our applications.

  1. Example 1

    const debounce = (callback, time = 300) => {
    let timer;

    return () => {
    clearTimeout(timer);
    timer = setTimeout(callback, time);
    };
    };

2. Throttling

Throttling is a technique similar to debouncing, as both are used to limit the frequency of function calls. The difference is that throttling does not clear the timer every time the function is called, but instead uses a pause condition to avoid creating new timers. In other words, while the function is being called, it will not wait until the last call to execute, but will only call the function if it enters the time interval where the pause is disabled

  1. Example 2

    const throttle = (callback, time = 300) => {
    let pause = false;


    return () => {
    if (pause) return;
    pause = true;
    callback();
    setTimeout(() => {
    pause = false;
    }, time);
    };
    };

3. Memoization

Memoization is a technique that involves storing the result of a function in a memory space that allows for later retrieval. This is done to avoid having to recalculate the result every time the function is called with the same parameters. This technique is used for functions that consume a lot of resources. In such cases, memoization can improve performance and speed in obtaining results.

This technique can be used in React as well, we can make use of the following memoization features in React:

  • React.memo

  • useMemo

  • useCallback

  1. Example 3

    const getFactorial = (n) => {
    if (n === 1 || n === 0) return 1;
    return n * getFactorial(n - 1);
    };

4. React.memo

This is a useful tool for avoiding unnecessary renders of components when the props they receive do not change. The purpose of React.memo is to improve application performance. However, it is important to note that React.memo will not prevent component renders caused by state or context (React.Context) updates, as it only considers props to avoid re-renders.

5. Pure Components

A React component is considered pure if it renders the same output for the same state and props. For this type of component, React provides the PureComponent class. Class components that extend the PureComponent class are treated as pure components. Pure components have some performance improvements and render optimizations since React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state.

6. Lazy Loading

React.lazy is a React technique that allows us to lazily import our components until the moment they are first rendered. This can be quite useful when we don’t want to import the entire bundle of components at once, as it can slow down the application’s load time. The idea behind React.lazy is to speed up the loading of a specific page by importing only what the page needs at that moment. This can be especially helpful in large or complex applications that contain many components.

7.Virtualization (Windowing)

React virtualization is a powerful technique for creating high-performing user interfaces that only display the elements currently in use. Whether you use a React virtualized library or build your own algorithm, the technique is specifically designed to handle large datasets and improve UI performance. By selectively rendering only the elements needed at any given time, virtualization in React leads to faster load times and a smoother user experience overall.

8.Error Boundaries

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, lifecycle methods, and constructors of the whole tree below them. It’s important to note that error boundaries do not catch errors for event handlers, asynchronous code, or errors that occur in the error boundary itself. You can find more details about error .

9.Inline Functions

There are several reasons why it is recommended to avoid using inline functions in React. Here are some of them:

  • Performance: Every time a component is rendered in React, all inline functions are recreated. This can lead to slower performance in your application, especially if you have many components with inline functions.

  • Maintenance: Inline functions are defined within the component and cannot be reused in other parts of the application. This can make the code more difficult to maintain as the application grows.

  • Readability: Inline functions can make code more difficult to read and understand, especially if they are long or have many arguments.

Gefällt dir dieser Beitrag?

Kaufe Syed Maaz Saeed einen Kaffee

Mehr von Syed Maaz Saeed