Home > Enterprise >  How to avoid nested map for better rendering performance?
How to avoid nested map for better rendering performance?

Time:09-26

I have this nested map that kind render slow after redirection I tried to map only the group and it was really fast, any idea how to get rid of this nesting yet achieve the same results? also could calling the function inside of return causing this dip.....

itemSet =  [
      { id: 1, group: 'A', item : 'someitem' },
      { id: 2, group: 'A',  item : 'someitem' },
      { id: 3, group: 'B',  item : 'someitem' },
      { id: 4, group: 'B', item : 'someitem' },
    ]

const groupItems = (items) =>
  items.reduce((group, items) => {
    if (!group[items.group]) {
      group[items.group] = [];
    }
    group[items.group].push(items);
    return group;
  }, {});

const items = (item) =>
    Object.entries(groupItems(item)).map(([group, items]) => (
      <React.Fragment>
        <group name={group} />
        {items.map((item) => (
          <item
            key={item.id}
            id={item.id}
            item={item.item}
          />
        ))}
      </React.Fragment>
    ));
  return (
    <MuiThemeProvider theme={themeDark}>
      <AppBar />
      <CssBaseline />
      {items(itemSet)}
    </MuiThemeProvider>
  );

CodePudding user response:

I believe your usecase is to render the array of array grouped by group. You will have to use the nested loops but you're missing key attribute in the first map. Try adding key there in the React.Fragment.

const items = (item) =>
    Object.entries(groupItems(item)).map(([group, items]) => (
      <React.Fragment key={group}>
        <group name={group} />
        {items.map((item) => (
          <item
            key={item.id}
            id={item.id}
            item={item.item}
          />
        ))}
      </React.Fragment>
    ));
  return (
    <MuiThemeProvider theme={themeDark}>
      <AppBar />
      <CssBaseline />
      {items(itemSet)}
    </MuiThemeProvider>
  );

Working example on codesandbox

  • Related