Skip to content
Source
Sign inSign up
TanStack/table

Can't perform a React state update on a component that hasn't mounted yet #5026

Closedtacomanator(GitHub profile, opens in a new tab) opened this issue 34 comments

Describe the bug

Error received when navigating to a table using getGroupedRowModel() such as:

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getGroupedRowModel: getGroupedRowModel(),
  });

As seen in this example, navigating to the basic table works fine where as navigating to the grouped table produces an error in the console. The only difference between the two is getGroupedRowModel().

I am using the code from the examples pretty much as is (stripped down for simplicity).

Your minimal, reproducible example

https://github.com/tacomanator/tanstack-table-unmounted

Steps to reproduce

  1. Clone example, install dependencies, and run
  2. While viewing the console, navigate to the grouped table
  3. Observe error

Expected behavior

No error output

How often does this bug happen?

Every time

Screenshots or Videos

https://github.com/TanStack/table/assets/63794/30edbbcf-8f7e-459f-b624-b7d82aac3f0a

Platform

macOS, Chrome 115.0.5790.170 arm64

react-table version

8.9.3

TypeScript version

5.1.6

Additional context

No response

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
  1. I am having the same problem in version 8.9.1 when I call table.getRowModel() to conditionally render rows in tbody and I can confirm that it probably has something to do with getGroupedRowModel.

    If i remove getGroupedRowModel: getGroupedRowModel() from the hook the error disappears.

  2. I'm seeing this exact same issue today.

  3. I investigated this issue this morning and discovered that the error only occurs when in dev mode. Same with @tacomanator's example. When I run the example in dev mode I get the error, but if I do a npm run build and npm start then the error disappears.

  4. I think this is due to the fact that these errors don't show up in production builds but still happen.

    Happy to be proven wrong.

  5. I think it has something to do with pagination. When you add getGroupedRowModel it ends up calling setPagination in the render and that ends up calling setState.

    So if you set onPaginationChange in the useReactTable definition to onPaginationChange: () => undefined then the error also goes away.

  6. vktrl(GitHub profile, opens in a new tab)commented

    I think this is due to the fact that these errors don't show up in production builds but still happen.

    It's possible that it's a dev-only error because of React's strict mode which will double renders and effects. For me it's happens only on the second round of the very first render.

    It's likely that there's a internal hook that's using useState in an useEffect for memoization. setState is called after the render but the component will already be unmounted in dev mode.

  7. This occurs here and exclusively in the context when the getGroupedRowModel function is utilized. It can be resolved by simply verifying whether the component is mounted before call setState in onStateChange. It seems somewhat hacky but can be helpful.

  8. This also happens on getFacetedUniqueValues

  9. same issue in getFacetedUniqueValues

  10. same issue in getFacetedUniqueValues

    also facing the same

  11. aaronlin0122(GitHub profile, opens in a new tab)commented

    same issue in getFacetedUniqueValues

    Same here, is there any other solution?

  12. I faced a similar issue. in my case, the affected functionality is due to function getSortedRowModel() from checking "isEmpty" of my data which this caused the error , my temporary solution is :

    getSortedRowModel: !data.isEmpty ? getSortedRowModel() : null

  13. 0ximjosh(GitHub profile, opens in a new tab)commented

    Using latest version of tanstack @ 8.11.6, getting this when calling table.getIsAllRowsSelected() in dev mode. I can confirm this still errors when strict mode is off.

    {
            id: "select-col",
            enableResizing: false,
            enableSorting: false,
            header: ({ table }) => (
              <div className="flex h-full w-full items-center justify-center">
                <input
                  type="checkbox"
                  className="rounded-sm bg-neutral-500 text-orange-600 focus:ring-0 focus:ring-offset-0"
                  id="checkbox"
                  checked={table.getIsAllRowsSelected()}
                  onChange={table.getToggleAllRowsSelectedHandler()}
                />
              </div>
            ),
          });
        }

    Temporary fix is to move the header component key into the actual rendering of the table and use an early check on the number of selected elements.

                    if (header.id === "select-col") {
                      return (
                        <div
                          key={header.id}
                          className="sticky left-0 top-0 z-20 border border-gray-600 bg-neutral-900 px-2.5 py-1.5"
                        >
                          <div className="flex h-full w-full items-center justify-center">
                            <input
                              type="checkbox"
                              className="rounded-sm bg-neutral-500 text-orange-600 focus:ring-0 focus:ring-offset-0"
                              id="checkbox"
                              checked={!!Object.keys(rowSelection) ? table.getIsAllRowsSelected() : false}
                              onChange={table.getToggleAllRowsSelectedHandler()}
                            />
                          </div>
                        </div>
                      );
                    }
  14. I receive this when using getRowModel but not when using any of the other getRow functions. Figure it's something getRowModel does during render.

  15. With me this error occurred in 8.20.1 as well, in table.getColumn(<COLUMN_ID>) in the Toolbar component, while passing column prop, and updating the DataTableFacetedFilter shadcn-ui component.

    Which is absolutely expected behavior when passing mutable props.

    Updating column prop via useState hook, solved the problem.

    const [statusCol, setStatusCol] = useState(null);
    
    useEffect(() => {
        if (table.getAllColumns().length) {
          setStatusCol(table.getColumn('status'));
        }
      }, [table.getAllColumns().length]);
    
    // then
    
    {statusCol && (
      <DataTableFacetedFilter
        column={statusCol}
        // ...
      />
    )}
  16. I receive this error as well. For now I disable getGroupedRowModel and the error is gone.

  17. I've been looking for a solution to this problem for a while. After reading further up about the pagination state causing the error I added manualPagination: true to the useReactTable hook props and it seems to fix it.

    My use case has no need for client side pagination, so I guess it would be ok to set manualPagination to true?

  18. nabilfatih(GitHub profile, opens in a new tab)commented

    just add:

    const [isMounted, setIsMounted] = React.useState(false)
    
      // Fix error on react table, when the table is not mounted
      React.useLayoutEffect(() => {
        setIsMounted(true)
      }, [])
    
    // react table hook, and other codes...
    
    // Fix error on react table, when the table is not mounted
      if (!isMounted) return null
  19. @nabilfatih as a workaround sure, but important to let people know this workaround will hurt performance and change the loading profile of their app.

  20. i get this same error on this line: table.getRowModel().rows?.length

  21. flaviodelgrosso(GitHub profile, opens in a new tab)commented

    Same problem here. Seems that getPaginationRowModel with getGroupedRowModel is causing the problem. tanstack table version 8.20.5. autoResetPageIndex: false seems to suppress the error but it messes up with filtering when changing the first page.

  22. adding this to hook useReactTable solved the issue for me:

    autoResetPageIndex: false,
  23. @ApacheEx

    I'm using table.getSelectedRowModel().rows.length I guess that doesn't help in my case.

  24. adding this to hook useReactTable solved the issue for me:

    autoResetPageIndex: false,

    Thank you. It works but I'm wondering why

  25. As @vktrl mentioned, this occurs in strict mode because React mounts and unmounts the component.

    The RowPagination feature will make a setState call (from calling resetPageIndex) if autoResetPageIndex is True, which is default (see here)

    I have a PR to fix this by tracking whether the component is mounted or not and only calling setState if it is

    https://github.com/TanStack/table/pull/5879/commits/f02386302c429937cc2f38ad7342335bf3ee516b

  26. Correct link to PR: https://github.com/TanStack/table/pull/5879. Wondering why there are no comments on it...

  27. ealexhaywood(GitHub profile, opens in a new tab)commented

    For anyone stumbling upon this in 2025, you probably don't want to turn off autoResetPageIndex (unless you are manually paging) and instead should go with the fix suggested by @nabilfatih https://github.com/TanStack/table/issues/5026#issuecomment-2315023555 until PR #5879 is accepted

    I like capturing that logic in a component:

    function ClientOnly({ children }) {
      const [hasMounted, setHasMounted] = useState(false);
    
      useEffect(() => { 
        setHasMounted(true);
      }, []);
    
      if (!hasMounted) return null;
    
      return children;
    }
    
    function MyComponent() {
      return (
        <ClientOnly>
          <MyReactTableComponent />
        </ClientOnly>
      )
    }
  28. My error was caused by getSelectedRowModel() and autoResetPageIndex: false fixed it.

  29. Correct link to PR: #5879. Wondering why there are no comments on it...

    Any updates on this? Love the library, and would prefer to avoid having to use a less than optimal workaround.

  30. I can confirm I am still seeing this issue with 8.21.3. autoResetPageIndex fixed this but would prefer the workaround in the PR here: https://github.com/TanStack/table/pull/5879 or something like it

  31. jconnorbuilds(GitHub profile, opens in a new tab)commented

    Adding on to the pile: I'm getting this error with getFilteredRowModel(), and autoResetPageIndex: false fixes it.

    Edit: @ealexhaywood 's workaround based on the open PR is a much better solution as it doesn't affect my paginated table view.

  32. This has to do with how options with the state option being used are synced during render under the hood. We don't have a good clean fix for this that doesn't also cause tons of additional problems yet. V8 or V9

  33. we think we finally fixed this in the latest v9 beta

  34. KevinVandy closed this

Sign in to join this conversation.