Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Effectively rendering lists in React.js

When you’re working on the frontend side of the things of a website, one of the most common tasks is to render lists from arrays/objects.

The way that you can do this in React is using the Array.prototype.map() method like so.

export default function App() {
  const list = [
    { key: 1, value: 10 },
    { key: 2, value: 20 },
    { key: 3, value: 30 }
  ];

  return (
    <div>
        {list.map(({ key, value }) => (
            <div key={key}>
                {value}
            </div>
        ))}
    </div>
  );
}

Now, this is pretty alright but let’s suppose the list has a significant amount of items and you’re doing some complex calculation while rendering the list. In that scenario, React will unnecessarily render the lists every time the component is called even if the items of the list array haven’t been changed.

This could be easily avoided by using the useMemo() hook.

Using the useMemo() hook

The idea is when you have a list that doesn’t get changed pretty frequently, we can offset its rendering to the useMemo() hook.

Here’s how can change the previous example to use the useMemo() hook.

import { useMemo } from 'react';

export default function App() {
  const list = [
    { key: 1, value: 10 },
    { key: 2, value: 20 },
    { key: 3, value: 30 }
  ];

  const renderedList = useMemo(() => (
    list.map(({ key, value }) => (
        <div key={key}>
            {value}
        </div>
    ))
  ), [list]);

  return (
    <div>
        {renderedList}
    </div>
  );
}

As you can tell, we can offset the rendering logic to the useMemo() hook where we can pass in the list as its dependency.

The useMemo() hook would return a memoized value of this rendered list. It will only recompute the memoized value when one of the dependencies (i.e. list) has changed. This optimization helps to avoid expensive calculations on every render.

And so, this could effectively reduce the amount of unnecessary rendering of lists and hence, improves the overall performance of the app!

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?