T
TanStack•3y ago
helpful-purple

Why does table reference not change, when data passed to useReactTable changes?

const table = useReactTable({ data, columns });
return (
<TableBody table={table} />; //<-- this is React component wrapped in memo()
);
const table = useReactTable({ data, columns });
return (
<TableBody table={table} />; //<-- this is React component wrapped in memo()
);
Because the table is constantly the same reference, it's impossible to pass it down to other memoized subcomponents. They never rerender, because table didn't change. Same applies if data is the same, but row selections are changed. What's the reason behind this behaviour? What's the correct approach to use this lib without packing everything into one huge single component?
1 Reply
foreign-sapphire
foreign-sapphire•3y ago
Hi @matleo, You could always use the Table<TData>.setOptions() method which allows you to pass a data property inside. Definition:
export interface CoreInstance<TData extends RowData> {
setOptions: (newOptions: Updater<TableOptionsResolved<TData>>) => void;
}
export interface CoreInstance<TData extends RowData> {
setOptions: (newOptions: Updater<TableOptionsResolved<TData>>) => void;
}
Let's say you created an instance of your table using the useReactTable hook. šŸ‘‰ You could do something like this:
const table = useReactTable({ data, columns });

useEffect(() => {
table.setOptions({
data: MY_NEW_DATA,
state: YOUR_STATE,
onStateChange: (updater: any) => {}, // Mandatory, put whatever inside
getCoreRowModel: getCoreRowModel(), // You get this from an import
columns: YOUR_COLUMNS,
renderFallbackValue: undefined, // Mandatory, put whatever inside
})
}, [dataWasChanged])
const table = useReactTable({ data, columns });

useEffect(() => {
table.setOptions({
data: MY_NEW_DATA,
state: YOUR_STATE,
onStateChange: (updater: any) => {}, // Mandatory, put whatever inside
getCoreRowModel: getCoreRowModel(), // You get this from an import
columns: YOUR_COLUMNS,
renderFallbackValue: undefined, // Mandatory, put whatever inside
})
}, [dataWasChanged])
The dataWasChanged property is whatever you need from your props for example to update the state. It could be props.data for example. It works well in my case and that's the best way I could find to update the table without packing everything into one or more components as you said. Is it what you wanted ? Tell me how it goes for you ! I encountered the same kind of challenge with my tables. They have basic data which is accessible when the table is created but some columns are missing some data because that data needs to be fetched in the background. With the setOptions() method, I can update the table properly when the extra data is fetched, cleaned and passed šŸ‘

Did you find this page helpful?