React Ant Design - best place to generate columns in functionnal component

Viewed 830

My app have a very intensive table usage. I generate quite complex tables, and filters are calculated automatically (map on array of values to get possible values in the current dataset for example). So basically my point is that it can be intensive on some pages.

What would be the best place to generate columns in a React App with Antdesign, performance wise? Note that we mostly use functionnal components, with useState hook when needed.

  • in a useState hook, and display the table once the generation fulfilled
  • directly in the <Table columns={generateCols()}>
  • something else?

IMO the good point of the first is that if the component re-render, it will not re-generate the columns, but I'm not sure about that. The second is simpler to maintain and less complex, but if a re-render implies generating again the columns, I'm not sure about the gain!

Thanks

Example of code with columns stored in useState (may be some typos, but you get the overall picture):

export function TableComponent(props: Props) {
  const { meal, similarMeals } = props;

  const [tableCols, setTableCols] = useState<ColumnProps<meal>[] | undefined>(
    undefined
  );

  useEffect(() => {
    setTableCols(
      generateSimilarMealColumns(
        meal.countOfIngredients,
        meal.similarMeals
      )
    );
  }, [meal.countOfIngredients, meal.similarMeals]);

  return (
    <>
      <Container className={styles.section}>
        {tableCols !== undefined ? (
          <Table<meal>
            rowKey="_id"
            columns={tableCols}
            dataSource={similarMeals}
            pagination={false}
            expandRowByClick={true}
            expandedRowRender={(record) => <p>{record.longDescription}</p>}
          />
        ) : (
          <Spin />
        )}
      </Container>
    </>
  );
}
1 Answers

Let me preface by saying don't prematurely do perf stuff. If it works, keep going until it doesn't.

Secondly, one thing that stands out to me is that you are calling a function to generate the columns every time your Table component is rendered. If the component rendering your Table component gets re-rendered, then you might be doing a bunch of extra work for no reason.

Show the rest of the component that renders your Table component - this might be a good use case for useMemo.

EDIT: As a possibility, you might be able to fix the whole thing simply by doing this:

<Table columns={useMemo(generateCols,[... list of dependencies that are used in here])}>

Related