Effectively rendering lists in React.js — Amit Merchant — A blog on PHP, JavaScript, and more

0
23

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 have not 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 does not get changed quite 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 (ie 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!

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here