I'm developing an app with React Query and React Table but table seems to break when I change the query key, thus causing the website to crash.
I opened an issue on their GH but I still have no response and really need a hand.
Here is a minimal reproduction of the issue: codesanbox
The crash happens when rendering the table (the table.getRowModel()
function to be exact), not when defining the actual columns or table. It also only happens when UPDATING the query keys, everything works fine on initial render.
Many thanks, Herbie
Problems with the code
queryFn: inside queryFn return filter operation was done based on successOrError
. Ideally filtered data should be returned from backend.
Whenever the component rerenders (for example when successOrError value is updated which is exactly when the page was crashing), if data is present, filter operation will run again, which in turn will update the table value and the component will rerender again. So this is how we get stuck in infinite loop of rerenders.
const table = useReactTable({
columns,
data: data
? data.filter((v) =>
successOrError === "success" ? v.status < 400 : v.status >= 400
)
: [],
getCoreRowModel: getCoreRowModel(),
});
SOLUTION:
Now, the memoizedData only changes when the dependencies change, and memoziedData is passed to table, and table only updates when memoizedData updates.
// MEMOIZE DATA to avoid infinite rerenders.
const memoizedData = useMemo(() => {
if (!data) return [];
return data.filter((v) =>
successOrError === "success" ? v.status < 400 : v.status >= 400
);
}, [data, successOrError]);