Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useMemo on function used in .map statement

I am pretty much new to hooks so have a question here: I have in React component function like

const getSection = assignmentSectionId => {
    const findSection = sections.find(
      section => section.sectionRefId === assignmentSectionId,
    );

    return findSection ? findSection.name : '';
  };

and now I got suggestion to use useMemo on that function. Currently I am using like:

return (
    <List
      role="list"
      aria-label={ariaLabel}
    >
      {assignments.map(assignment => {
        const sectionName = getSection(assignment.sectionId);

        return (
          <Card
            name={sectionName}
          />
        );
      })}
    </List>
  );
};

What is the best(optimal) way to use useMemo here if it is possible?

like image 725
Galiant Avatar asked May 16 '26 13:05

Galiant


1 Answers

You could use the Array#map inside the useMemo .Its only re-render the list After assignments value change

const memoList = React.useMemo(()=> assignments.map(assignment => {
        const sectionName = getSection(assignment.sectionId);
        return (<Card  name={sectionName}/>)
      }),[assignments])

return (
    <List role="list" aria-label={ariaLabel}>{memoList}</List>
  );
};
like image 164
prasanth Avatar answered May 19 '26 03:05

prasanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!