Performance Optimization in React

As web applications become more and more complex, they often become increasingly bloated, making the app less responsive. As developers, we must start to think about how to optimize our app so that they provide better user experience.

In this lesson, we are going to cover some of the tools React has provided us to help optimize our apps.

Memorizing the result of a function

Sometimes you may have functions performing "expensive" tasks in your program, operations that consume significant time or system resources. In this case, you could let React memorize the result of that function with the useMemo() hook:

jsx
1import { useState, useMemo } from "react";
2
3function SquareCalculator() {
4  const [number, setNumber] = useState(0);
5  const [counter, setCounter] = useState(0);
6
7  const squaredNum = useMemo(
8    function square() {
9      console.log("Calculating square...");
10      return number * number;
11    },
12    [number]
13  );
14
15  return (
16    <>
17      <div>
18        <input
19          type="number"
20          value={number}
21          onChange={(e) => setNumber(Number(e.target.value))}
22        />
23        <p>
24          Square of {number}: {squaredNum}
25        </p>
26      </div>
27
28      <div>
29        <p>Counter: {counter}</p>
30        <button onClick={() => setCounter(counter + 1)}>
31          Increment Counter
32        </button>
33      </div>
34    </>
35  );
36}
37
38export default SquareCalculator;

In this example, pay attention to line 7 to 13. The function square() will calculate and return the square of number. The returned value will be saved to the variable squaredNum. As lone as number does not change, the function square() will not be executed. The saved value will be preserved between renders.

To verify this, open the browser console and type inside the input box. This will update number, and causing square() to recalculate. You should see Calculating square... being logged to the console.

However, when you click on the Increment Counter button, this will cause the component to be rendered, but notice that the function square() is not executed, and the saved value, squaredNum, is not lost either.

Memorizing a component

Besides memorizing the result of a function, it is also possible for React to memorize an entire component. memo() allows a component to skip re-rendering, as long as its props do not change. For example:

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉