|
| 1 | +import { useMemo, useRef } from 'react'; |
| 2 | +import { |
| 3 | + decodeFeedQueryResult, |
| 4 | + type PostData, |
| 5 | +} from '@/src/common/lib/polycentric-hooks'; |
| 6 | + |
| 7 | +// Mirror the list's keyExtractor (`FeedList` keys rows by `repostId ?? id`). |
| 8 | +const keyOf = (item: PostData) => item.repostId ?? item.id; |
| 9 | + |
| 10 | +/** |
| 11 | + * Decode a feed query buffer into items while preserving the object |
| 12 | + * reference for posts we've already decoded. |
| 13 | + * |
| 14 | + * Every `extend()`/`refresh()` produces a brand-new merged buffer, so a |
| 15 | + * naive `decodeFeedQueryResult(data)` rebuilds *every* `PostData` object. |
| 16 | + * That changes the `post` prop identity of every already-rendered row, so |
| 17 | + * all the memoized `Post` cells re-render at once and FlashList re-lays-out |
| 18 | + * the whole list — the previous items visibly flash on load-more. |
| 19 | + * |
| 20 | + * Polycentric posts are immutable content-addressed events, so the decoded |
| 21 | + * value for a given key never changes. We can therefore reuse the prior |
| 22 | + * reference for any key we've already seen: unchanged rows keep their |
| 23 | + * identity (and skip re-rendering), while only genuinely new rows mount. |
| 24 | + */ |
| 25 | +export function useStableFeedItems( |
| 26 | + data: ArrayBuffer | undefined, |
| 27 | +): [PostData[], boolean] { |
| 28 | + const cache = useRef<Map<string, PostData>>(new Map()); |
| 29 | + |
| 30 | + return useMemo(() => { |
| 31 | + const [decoded, hasNext] = decodeFeedQueryResult(data); |
| 32 | + const next = new Map<string, PostData>(); |
| 33 | + const items = decoded.map((item) => { |
| 34 | + const key = keyOf(item); |
| 35 | + const stable = cache.current.get(key) ?? item; |
| 36 | + next.set(key, stable); |
| 37 | + return stable; |
| 38 | + }); |
| 39 | + cache.current = next; |
| 40 | + return [items, hasNext]; |
| 41 | + }, [data]); |
| 42 | +} |
0 commit comments