useVirtualizedList.tsx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import {DependencyList, RefObject, useCallback, useEffect, useMemo} from 'react';
  2. import {CellMeasurerCache, CellMeasurerCacheParams, List} from 'react-virtualized';
  3. type Opts = {
  4. cellMeasurer: CellMeasurerCacheParams;
  5. deps: DependencyList;
  6. ref: RefObject<List>;
  7. };
  8. function useVirtualizedList({cellMeasurer, deps, ref}: Opts) {
  9. const cache = useMemo(() => new CellMeasurerCache(cellMeasurer), [cellMeasurer]);
  10. const updateList = useCallback(() => {
  11. cache.clearAll();
  12. ref.current?.forceUpdateGrid();
  13. }, [cache, ref]);
  14. // Restart cache when items changes
  15. // XXX: this has potential to break the UI, especially with dynamic content
  16. // in lists (e.g. ObjectInspector). Consider removing this as deps can easily
  17. // be forgotten to be memoized.
  18. //
  19. // The reason for high potential to break UI: updateList clears the cache, so
  20. // any cells that were expanded but scrolled out of view will have their
  21. // cached heights reset while they re-render expanded.
  22. useEffect(() => {
  23. updateList();
  24. }, [updateList, deps]);
  25. return {
  26. cache,
  27. updateList,
  28. };
  29. }
  30. export default useVirtualizedList;