Skip to content
Source
Sign inSign up
TanStack/virtual

React Compiler: useVirtual results are cached at their initial values #736

Send to my agent
Closedgdorsi(GitHub profile, opens in a new tab) opened this issue 14 comments

Describe the bug

An usage of useVirtual gets compiled by React Compiler into something like this:

const virtualizer = (0,
_tanstack_react_virtual__WEBPACK_IMPORTED_MODULE_9__.useVirtualizer)(t3);
let t4;
if ($[9] !== virtualizer) {
  t4 = virtualizer.getVirtualItems();
  $[9] = virtualizer;
  $[10] = t4;
} else {
  t4 = $[10];
}

Since the virtualizer ref never changes, the virtual items never get updated.

Not sure if this should be a Tanstack Virtual issue or React Compiler needs to apply less assumptions when caching values, but thought that would be good to flag the problem here.

Wrapping useVirtual into something like this fixes the issue:

const useVirtualWrapper = (...args) => {
  'use no memo';
  return { ...useVirtual(...args) };
}

Your minimal, reproducible example

https://codesandbox.io/p/devbox/runtime-dew-9rlvm7

Steps to reproduce

  1. Open the example (forked from https://tanstack.com/virtual/latest/docs/framework/react/examples/fixed)
  2. The virtual lists are rendering no items

Expected behavior

The UI should be the same as https://tanstack.com/virtual/latest/docs/framework/react/examples/fixed

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • MacOS, Chrome and Firefox

tanstack-virtual version

3.5.0

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.
  1. gdorsi(GitHub profile, opens in a new tab) changed the title

  2. Similar thing happens if the component is wrapped in memo. @tannerlinsley this error only shows up with strict mode off (i.e. in production).

  3. Specifying initialRect made it work for me

  4. got same problem, very annoying when using react-compiler. My workaround was to save an instance of virtualizer as state when the onChange function is saved, and use that instance in my component instead of the instance returned by the hook.

        const [virtualizer, setVirtualizer] = useState<Virtualizer<HTMLDivElement, Element> | null>(null);
    
        useVirtualizer({
            count: data.getCount(),
            estimateSize: () => 30,
            getScrollElement: () => scrollableRef.current,
            onChange: (i) => setVirtualizer(i),
        });
    
       ....
        <>
           virtualizer?.getVirtualItems().map(v => {
              ....
           }
        </>

    any official solution or hint?

  5. 'use no memo' seems like a reasonable temporary workaround! https://react.dev/learn/react-compiler#something-is-not-working-after-compilation

  6. Specifying initialRect made it work for me

    Can you show how exactly did you get it?

  7. export default function VirtualList() {
      // opt out of react compiler
      'use no memo';
    }

    this works for me

  8. Here's a solution that works with TS and pretty strict eslint rules (e.g. where spreading classes is forbidden)

    const useVirtual = (options: Parameters<typeof useVirtualizer>[0]) => {
      'use no memo';
    
      const { getVirtualItems, getTotalSize } = useVirtualizer(options);
    
      return { virtualItems: getVirtualItems(), totalSize: getTotalSize(), /*...and whatever else you need*/ };
    };

    But I'd also like to understand how the virtualizer triggers a rerender in the first place if its reference remains stable (which it seems to be according to the compiler output). How does React notice a change if you need to call getVirtualItems during a render to get new items?

    The issue could be fixed by returning 'reactive' things directly as new references instead of returning a function to call, e.g returning virtualItems as an array instead of getVirtualItems as a function. This way the virtualizer can remain stable and you can opt into each feature that should rerender your component by simply destructuring what you need.

    Something like this

     const { virtualItems, totalSize } = useVirtual({
          count: items.length,
          getScrollElement: () => scrollRef.current,
          estimateSize: () => rowHeight
        });
  9. any news on actually fixing the issue? "use no memo" directive is just a workaround and the related PR seems to have been closed almost a year ago #851

  10. I've published a compiler-compatible package that is a near drop-in replacement for @tanstack/react-virtual: react-hook-tanstack-virtual.

  11. React Compiler compatibility is now solved with directDomUpdates

    The root cause is that React Compiler caches virtualizer.getVirtualItems() against the stable virtualizer reference — since the reference never changes, the compiler assumes the return value is also stable, so scroll-driven updates never reach the DOM.

    The new directDomUpdates option bypasses this entirely: item positions and container size are written directly to the DOM, and React only re-renders when the visible index range changes. This makes the virtualizer fully compatible with React Compiler without any workarounds ('use no memo', spreading, etc.).

    const virtualizer = useVirtualizer({
      count,
      getScrollElement: () => parentRef.current,
      estimateSize: () => 50,
      directDomUpdates: true, // skips React for position updates
      directDomUpdatesMode: 'transform', // or 'position'
    })
    
    // The inner container must use containerRef (not getTotalSize() in style):
    <div ref={virtualizer.containerRef} style={{ position: 'relative' }}>
      {virtualizer.getVirtualItems().map((item) => (
        <div
          key={item.key}
          ref={virtualizer.measureElement}
          data-index={item.index}
          style={{ position: 'absolute', top: 0, left: 0, width: '100%' }}
        >
          Row {item.index}
        </div>
      ))}
    </div>

    We've added an e2e test that builds the fixture app with babel-plugin-react-compiler enabled and verifies items render and update correctly after scrolling.

  12. piecyk closed this

  13. Quick question to make sure we're using directDomUpdates correctly.

    We followed the pattern from this comment (directDomUpdates: true, containerRef, getVirtualItems(), measureElement) on @tanstack/react-virtual@3.14.2 with babel-plugin-react-compiler@1.0.0.

    Runtime seems to work. But the compiler still bails on the component:

      [react-compiler] CompileError
      Refs: Cannot access refs during render
        · Cannot access ref value during render            → virtualizer.containerRef
        · Passing a ref to a function may read its value   → virtualizer.getVirtualItems()

    It reproduces with essentially the fixture pattern, minimal repro:

      function Probe() {
        const parentRef = useRef<HTMLDivElement>(null)
        const virtualizer = useVirtualizer({
          count: 1000,
          getScrollElement: () => parentRef.current,
          estimateSize: () => 50,
          directDomUpdates: true,
          directDomUpdatesMode: 'transform',
        })
        return (
          <div ref={parentRef} style={{ overflow: 'auto', height: 400 }}>
            <div ref={virtualizer.containerRef} style={{ position: 'relative' }}>
              {virtualizer.getVirtualItems().map((item) => (
                <div key={item.key} ref={virtualizer.measureElement} data-index={item.index}
                     style={{ position: 'absolute', top: 0, left: 0, width: '100%' }}>
                  Row {item.index}
                </div>
              ))}
            </div>
          </div>
        )
      }

    So the question: is this CompileError expected? i.e. "compatible" means the component is left uncompiled but directDomUpdates keeps it correct (and the e2e test validates runtime rather than a clean compile)? Or is the documented pattern meant to compile with no diagnostics, and we've got something wrong in our setup?

    If bailing-but-correct is the intended end state, would you still recommend a "use no memo" on the component to quiet the diagnostic, or just leave it?

    (One extra data point: useWindowVirtualizer emits 3 of these diagnostics vs useVirtualizer's 1, but both bail and both work at runtime.)

    Thanks!

  14. @eikowagenknecht Yes, this is a known issue. react-virtual was added to React’s known incompatible libraries here: https://github.com/facebook/react/pull/34493

    If you use directDomUpdates, it should make it compatible, so you can suppress this warning for now.

    We still need to address this properly on our side.

    Btw, what do you think about directDomUpdates? Have you noticed any issues on your side?

  15. Btw, @eikowagenknecht, I’d also add overflow-anchor: none to the scrolling container. Sometimes the browser’s scroll anchoring conflicts with virtualization, so it’s better to disable automatic scroll adjustment.

    <div ref={parentRef} style={{ overflow: 'auto', height: 400, overflowAnchor: 'none' }}>

Sign in to join this conversation.