diff --git a/.changeset/fix-toggle-expanded-noop.md b/.changeset/fix-toggle-expanded-noop.md new file mode 100644 index 0000000000..360084523d --- /dev/null +++ b/.changeset/fix-toggle-expanded-noop.md @@ -0,0 +1,5 @@ +--- +'@tanstack/table-core': patch +--- + +Skip state update in toggleExpanded when the desired state matches the current state, avoiding unnecessary re-renders diff --git a/packages/table-core/src/features/RowExpanding.ts b/packages/table-core/src/features/RowExpanding.ts index 456108d4d4..fb190768d0 100644 --- a/packages/table-core/src/features/RowExpanding.ts +++ b/packages/table-core/src/features/RowExpanding.ts @@ -290,9 +290,16 @@ export const RowExpanding: TableFeature = { table: Table, ): void => { row.toggleExpanded = (expanded) => { - table.setExpanded((old) => { - const exists = old === true ? true : !!old?.[row.id] + const isCurrentlyExpanded = row.getIsExpanded() + const newExpanded = expanded ?? !isCurrentlyExpanded + + // If the desired state matches the current state, skip the update + // to avoid unnecessary re-renders + if (newExpanded === isCurrentlyExpanded) { + return + } + table.setExpanded((old) => { let oldExpanded: ExpandedStateList = {} if (old === true) { @@ -303,21 +310,15 @@ export const RowExpanding: TableFeature = { oldExpanded = old } - expanded = expanded ?? !exists - - if (!exists && expanded) { + if (newExpanded) { return { ...oldExpanded, [row.id]: true, } } - if (exists && !expanded) { - const { [row.id]: _, ...rest } = oldExpanded - return rest - } - - return old + const { [row.id]: _, ...rest } = oldExpanded + return rest }) } row.getIsExpanded = () => {