Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-toggle-expanded-noop.md
Original file line number Diff line number Diff line change
@@ -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
23 changes: 12 additions & 11 deletions packages/table-core/src/features/RowExpanding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,16 @@ export const RowExpanding: TableFeature = {
table: Table<TData>,
): 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) {
Expand All @@ -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 = () => {
Expand Down