Skip to content

Commit b012536

Browse files
committed
perf(RepoView): Optimize ImageCell re-renders on scroll
- Cache onClick handlers in Map to provide stable references - Memoize repo object to ensure stable reference - Optimize itemRenderer dependencies to prevent recreation - Prevent ImageCell re-renders when scrolling
1 parent dc17e96 commit b012536

1 file changed

Lines changed: 18 additions & 7 deletions

File tree

src/pages/RepoView.tsx

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {useCallback, useEffect, useMemo, useState} from 'react'
1+
import {useCallback, useEffect, useMemo, useState, useRef} from 'react'
22

33
import {
44
VirtualizedFlexGrid,
@@ -177,24 +177,35 @@ export default function RepoView() {
177177
setViewerOpen(true)
178178
}, [])
179179

180-
// Create stable click handlers for each item to avoid recreating functions
181-
const createItemClickHandler = useCallback(
182-
(index: number) => () => handleImageClick(index),
180+
// Create stable click handlers map to avoid recreating functions
181+
const clickHandlersRef = useRef<Map<number, () => void>>(new Map())
182+
183+
const getClickHandler = useCallback(
184+
(index: number) => {
185+
if (!clickHandlersRef.current.has(index)) {
186+
clickHandlersRef.current.set(index, () => handleImageClick(index))
187+
}
188+
return clickHandlersRef.current.get(index)!
189+
},
183190
[handleImageClick],
184191
)
185192

193+
// Memoize repo to ensure stable reference
194+
// useTargetRepository already memoizes, but we ensure it's stable here too
195+
const stableRepo = useMemo(() => repo, [repo])
196+
186197
const itemRenderer = useCallback(
187198
({index, item}: RenderData<string>) => (
188199
<ImageCell
189200
key={index}
190-
repo={repo}
201+
repo={stableRepo}
191202
path={item}
192-
onClick={createItemClickHandler(index)}
203+
onClick={getClickHandler(index)}
193204
mcmetaPaths={mcmetaPaths}
194205
animationEnabled={animationEnabled}
195206
/>
196207
),
197-
[repo, createItemClickHandler, mcmetaPaths, animationEnabled],
208+
[stableRepo, getClickHandler, mcmetaPaths, animationEnabled],
198209
)
199210
const downloadFilteredImages = useCallback(async () => {
200211
const paths = filteredImageFiles || []

0 commit comments

Comments
 (0)