| 21 | } |
| 22 | |
| 23 | export function useDynamicRowHeight({ |
| 24 | defaultRowHeight, |
| 25 | initialRowHeights, |
| 26 | key |
| 27 | }: { |
| 28 | /** |
| 29 | * Estimated height (in pixels) of rows that have not yet been measured. |
| 30 | */ |
| 31 | defaultRowHeight: number; |
| 32 | |
| 33 | /** |
| 34 | * Row heights (in pixels) that are known or can be estimated ahead of time, e.g. estimated from each row's content. |
| 35 | * This can be either an array (where each item is the height of the row at that index) or a Map of row index to height. |
| 36 | * |
| 37 | * These values are used in place of `defaultRowHeight` until rows are rendered and measured, |
| 38 | * so providing them can make server-rendered lists and initial scroll positions more accurate. |
| 39 | * |
| 40 | * ℹ️ This value is only read when the hook first mounts and when the `key` changes. |
| 41 | */ |
| 42 | initialRowHeights?: ReadonlyMap<number, number> | readonly number[]; |
| 43 | |
| 44 | /** |
| 45 | * Changing this value clears all measured row heights, |
| 46 | * e.g. when the list renders a different set of data. |
| 47 | */ |
| 48 | key?: string | number; |
| 49 | }) { |
| 50 | const [state, setState] = useState<{ |
| 51 | key: string | number | undefined; |
| 52 | map: Map<number, number>; |
| 53 | }>(() => ({ |
| 54 | key, |
| 55 | map: createInitialMap(initialRowHeights) |
| 56 | })); |
| 57 | |
| 58 | if (state.key !== key) { |
| 59 | setState({ |
| 60 | key, |
| 61 | map: createInitialMap(initialRowHeights) |
| 62 | }); |
| 63 | } |
| 64 | |
| 65 | const { map } = state; |
| 66 | |
| 67 | const getAverageRowHeight = useCallback(() => { |
| 68 | let totalHeight = 0; |
| 69 | |
| 70 | map.forEach((height) => { |
| 71 | totalHeight += height; |
| 72 | }); |
| 73 | |
| 74 | if (totalHeight === 0) { |
| 75 | return defaultRowHeight; |
| 76 | } |
| 77 | |
| 78 | return totalHeight / map.size; |
| 79 | }, [defaultRowHeight, map]); |
| 80 | |