Home > Software engineering >  React memo rerenders subsequent table rows when adding or deleting from table start
React memo rerenders subsequent table rows when adding or deleting from table start

Time:11-11

I have a table where each row is inside React.memo. Inside that memoized component, I have custom function-comparator. But each time I add rows to the table start, or delete rows from the start, the table rerenders every row.

Example: Add row to the table end => All OK, no extra rerenders. Add row to the table start => each row rerenders its contents.

I want my memo to NOT rerender each table row when I delete one.

Table row code:

const RowMemo = React.memo(({ row, rowIndex }) => {
  console.log('RowMemo renders');
  return <tr key={row.id} className="tr">
{"some contents"}
  </tr>
}, function compare(prev, next) {
  let keysToCompare = ['row', 'rowIndex']

  let isSame = true
  let diffKeys = []
  for (let key of keysToCompare) {
    if (prev[key] != next[key]) {
      diffKeys.push(key)
      // console.log('diff key', key) // shows that only row differs
    }
  }
  if (diffKeys.length) {
    isSame = false;
  }

  if (!isSame)
    console.log('isSame', isSame, prev.row == next.row, prev.row.id, next.row.id); // different rows, that's why it re-renders. 

  return isSame;
})

Rows rendering is plain and simple:

myRows.map((row, rowIndex) =>
                  <RowMemo {...{ row, rowIndex }} />
                )

Deleting a row is also plain and simple:

function removeTableProgramFormList(e, row) {
    setTableProgramFormList(prevState => prevState.filter(row => row != row));
  }

CodePudding user response:

You should add the key property one level higher, where you iterate and render the RowMemo components.

myRows.map((row, rowIndex) =>
                  <RowMemo key={row.id} {...{ row, rowIndex }} />
                )
  • Related