Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React memo rerenders subsequent table rows when adding or deleting from table start

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
  }

>Solution :

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 }} />
                )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading