From 7d546c8b34619ecd50ef6a69bc79204306803098 Mon Sep 17 00:00:00 2001 From: Guido D'Orsi Date: Thu, 10 Oct 2024 14:09:28 +0200 Subject: [PATCH] feat(react): compatibility with the React compiler --- packages/react-virtual/src/index.tsx | 2 +- packages/react-virtual/tests/index.test.tsx | 27 ++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/react-virtual/src/index.tsx b/packages/react-virtual/src/index.tsx index 3c4a4c98..4f1af0af 100644 --- a/packages/react-virtual/src/index.tsx +++ b/packages/react-virtual/src/index.tsx @@ -50,7 +50,7 @@ function useVirtualizerBase< return instance._willUpdate() }) - return instance + return React.useMemo(() => Object.create(instance), [instance.getVirtualItems()]) } export function useVirtualizer< diff --git a/packages/react-virtual/tests/index.test.tsx b/packages/react-virtual/tests/index.test.tsx index c7348dc2..44a1afe2 100644 --- a/packages/react-virtual/tests/index.test.tsx +++ b/packages/react-virtual/tests/index.test.tsx @@ -1,6 +1,6 @@ import { beforeEach, test, expect, vi } from 'vitest' import * as React from 'react' -import { render, screen, fireEvent } from '@testing-library/react' +import { render, screen, fireEvent, renderHook } from '@testing-library/react' import { useVirtualizer, Range } from '../src/index' @@ -190,3 +190,28 @@ test('should handle handle height change', () => { rerender() expect(screen.queryByText('Row 0')).toBeInTheDocument() }) + +test('should refresh the virtualizer instance when the items are changing (React Compiler)', () => { + const scrollElement = document.createElement('div') + const { rerender, result } = renderHook( + (props) => + useVirtualizer({ + count: props.count, + getScrollElement: () => scrollElement, + estimateSize: () => 50, + observeElementRect: (_, cb) => { + cb({ height: 100, width: 100 }) + }, + measureElement: () => 50, + }), + { + initialProps: { count: 0 }, + }, + ) + + const initialVirtualizer = result.current; + + rerender({ count: 10 }); + + expect(result.current).not.toBe(initialVirtualizer) +})