Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixup: spike - avoid calls to setState during initial render #1

Open
wants to merge 2 commits into
base: bwittenberg/3951
Choose a base branch
from
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
28 changes: 27 additions & 1 deletion packages/react/src/DataTable/__tests__/DataTable.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import userEvent from '@testing-library/user-event'
import {render, screen, queryAllByRole} from '@testing-library/react'
import React from 'react'
import React, {Profiler, type ComponentProps} from 'react'
import {DataTable, Table} from '../../DataTable'
import type {Column} from '../column'
import {createColumnHelper} from '../column'
Expand Down Expand Up @@ -1036,4 +1036,30 @@ describe('DataTable', () => {
})
})
})

describe('performance tests', () => {
it('should not render twice on initial render', () => {
type Data = {id: string; value: string}
const columns: ComponentProps<typeof DataTable<Data>>['columns'] = [
{
header: 'Value',
field: 'value',
},
]
const data: ComponentProps<typeof DataTable<Data>>['data'] = [
{
id: '1',
value: 'one',
},
]
let renderCount = 0
render(
<Profiler id="DataTable" onRender={() => renderCount++}>
<DataTable data={data} columns={columns} />
</Profiler>,
)

expect(renderCount).toBe(1)
})
})
})
145 changes: 76 additions & 69 deletions packages/react/src/DataTable/useTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ export function useTable<Data extends UniqueRow>({
initialSortColumn,
initialSortDirection,
}: TableConfig<Data>): Table<Data> {
const [rowOrder, setRowOrder] = useState(data)
const [prevData, setPrevData] = useState<typeof data | null>(null)
const [prevData, setPrevData] = useState(data)
const [prevColumns, setPrevColumns] = useState(columns)
const [sortByColumn, setSortByColumn] = useState<ColumnSortState>(() => {
return getInitialSortState(columns, initialSortColumn, initialSortDirection)
Expand Down Expand Up @@ -93,12 +92,14 @@ export function useTable<Data extends UniqueRow>({
}
})

const [sortedData, setSortedData] = useState(sortByColumn ? sortData({data, sortState: sortByColumn, headers}) : data)

// Update the row order and apply the current sort column to the incoming data
if (data !== prevData) {
setPrevData(data)
setRowOrder(data)
setSortedData(data)
if (sortByColumn) {
sortRows(sortByColumn)
setSortedData(sortData({data, sortState: sortByColumn, headers}))
}
}

Expand All @@ -112,75 +113,12 @@ export function useTable<Data extends UniqueRow>({
sortByColumn && sortByColumn.id === header.id ? transition(sortByColumn.direction) : DEFAULT_SORT_DIRECTION,
}
setSortByColumn(sortState)
sortRows(sortState)
}

/**
* Sort the rows of a table with the given column sort state. If the data in the table is sparse,
* blank values will be ordered last regardless of the sort direction.
*/
function sortRows(state: Exclude<ColumnSortState, null>) {
const header = headers.find(header => {
return header.id === state.id
})
if (!header) {
throw new Error(`Unable to find header with id: ${state.id}`)
}

if (header.column.sortBy === false || header.column.sortBy === undefined) {
throw new Error(`The column for this header is not sortable`)
}

const sortMethod =
header.column.sortBy === true
? strategies.basic
: typeof header.column.sortBy === 'string'
? strategies[header.column.sortBy]
: header.column.sortBy

setRowOrder(rowOrder => {
return rowOrder.slice().sort((a, b) => {
if (header.column.field === undefined) {
return 0
}

// Custom sort functions operate on the row versus the field
if (typeof header.column.sortBy === 'function') {
if (state.direction === SortDirection.ASC) {
// @ts-ignore todo
return sortMethod(a, b)
}
// @ts-ignore todo
return sortMethod(b, a)
}

const valueA = get(a, header.column.field)
const valueB = get(b, header.column.field)

if (valueA && valueB) {
if (state.direction === SortDirection.ASC) {
// @ts-ignore todo
return sortMethod(valueA, valueB)
}
// @ts-ignore todo
return sortMethod(valueB, valueA)
}

if (valueA) {
return -1
}

if (valueB) {
return 1
}
return 0
})
})
setSortedData(sortData({data, sortState, headers}))
}

return {
headers,
rows: rowOrder.map(row => {
rows: sortedData.map(row => {
return {
id: `${row.id}`,
getValue() {
Expand Down Expand Up @@ -210,6 +148,75 @@ export function useTable<Data extends UniqueRow>({
}
}

/**
* Sort the rows of a table with the given column sort state. If the data in the table is sparse,
* blank values will be ordered last regardless of the sort direction.
*/
function sortData<Data extends UniqueRow>({
data,
sortState,
headers,
}: {
data: Data[]
sortState: Exclude<ColumnSortState, null>
headers: Header<Data>[]
}) {
const header = headers.find(header => {
return header.id === sortState.id
})
if (!header) {
throw new Error(`Unable to find header with id: ${sortState.id}`)
}

if (header.column.sortBy === false || header.column.sortBy === undefined) {
throw new Error(`The column for this header is not sortable`)
}

const sortMethod =
header.column.sortBy === true
? strategies.basic
: typeof header.column.sortBy === 'string'
? strategies[header.column.sortBy]
: header.column.sortBy

return data.slice().sort((a, b) => {
if (header.column.field === undefined) {
return 0
}

// Custom sort functions operate on the row versus the field
if (typeof header.column.sortBy === 'function') {
if (sortState.direction === SortDirection.ASC) {
// @ts-ignore todo
return sortMethod(a, b)
}
// @ts-ignore todo
return sortMethod(b, a)
}

const valueA = get(a, header.column.field)
const valueB = get(b, header.column.field)

if (valueA && valueB) {
if (sortState.direction === SortDirection.ASC) {
// @ts-ignore todo
return sortMethod(valueA, valueB)
}
// @ts-ignore todo
return sortMethod(valueB, valueA)
}

if (valueA) {
return -1
}

if (valueB) {
return 1
}
return 0
})
}

function getInitialSortState<Data extends UniqueRow>(
columns: Array<Column<Data>>,
initialSortColumn?: string | number,
Expand Down