When to use useMemo

In React, there are times when we need to perform some expensive computations or function calls, especially when rendering complex components. This can lead to performance issues, as the computation has to be re-executed every time the component is re-rendered, even if the input parameters remain the same. To solve this problem, React provides a hook called useMemo.

useMemo is a hook that allows you to memoize the results of an expensive function call, and only recompute the result if the input parameters have changed. The basic syntax for useMemo is as follows:

const memoizedValue = useMemo(() => {
// expensive function call or computation
return result;
}, [input1, input2]);

The first argument to useMemo is a function that computes the value that needs to be memoized. The second argument is an array of input values that the function depends on. If any of the input values change, the memoized value will be recomputed. Let's take an example to understand how useMemo works in practice. Consider a component that renders a list of numbers and their squares:

function NumberList({ numbers }) {
return (
    <ul>
    {numbers.map((num) => (
        <li key={num}>
            {num} squared is {num * num}
        </li>
    ))}
    </ul>
    );
}

This component works fine for small lists, but can become slow for large lists as the computation of squares is done every time the component is rendered. To solve this, we can use useMemo to memoize the computation of squares:

function NumberList({ numbers }) {
    const squares = useMemo(() => {
        return numbers.map((num) => num * num);
    }, [numbers]);

    return (
        <ul>
            {numbers.map((num, index) => (
                <li key={num}>
                    {num} squared is {squares[index]}
                </li>
            ))}
        </ul>
    );
}

In this example, we use useMemo to memoize the computation of squares. The squares array is only recomputed when the numbers array changes. As a result, the component renders faster and performs better.

In summary, useMemo is a useful hook for optimizing the performance of your React components. It allows you to memoize expensive computations and function calls, and only recompute the result if the input parameters have changed. By using useMemo, you can ensure that your components render quickly and efficiently, even for large or complex data sets.

All articles are my own thoughts. Gathered from reading articles and trying things out.