Skip to content

flushSync was called from inside a lifecycle method #628

@sunwrobert

Description

@sunwrobert

Describe the bug

When using window virtualization, I see the following error in the console:

react-dom.development.js:94 Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.

This flushSync seems to have been added in #608. @piecyk have any recommendations?

I was able to fix this locally by guarding the cb with a isMounted check.

  const observeElementOffset: VirtualizerOptions<
    Window,
    Element
  >["observeElementOffset"] = useCallback(
    (instance, cb) => {
      const tableTopOffset = tableRef.current?.offsetTop ?? 0
      return observeWindowOffset(instance, offset => {
        // Observing the offset during lifecycle methods causes this error, so guard it by mounted.
        // Warning: flushSync was called from inside a lifecycle method.
        // React cannot flush when React is already rendering.
        // Consider moving this call to a scheduler task or micro task.
        // https://github.com/TanStack/virtual/pull/608
        if (isMountedRef.current) {
          cb(offset - tableTopOffset)
        }
      })
    },
    [tableRef],
  )

Your minimal, reproducible example

https://codesandbox.io/p/devbox/cool-haze-j7xfp5?file=%2Fsrc%2Fmain.tsx%3A19%2C30

Steps to reproduce

  1. Open console
  2. Notice flushSync error pops up on initial load

Expected behavior

There should not be a console error.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

Chrome

tanstack-virtual version

3.0.0-beta.68

TypeScript version

No response

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions