From 69126539065fde33a6ec4872cfaf3e61776f53f7 Mon Sep 17 00:00:00 2001 From: Gabriel Kaszewski Date: Sat, 11 Jul 2026 22:39:46 +0200 Subject: [PATCH] fix(app): cache useFavorites snapshot to prevent infinite re-render --- app/app/hooks/use-favorites.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/app/app/hooks/use-favorites.ts b/app/app/hooks/use-favorites.ts index 48e44dd..891332f 100644 --- a/app/app/hooks/use-favorites.ts +++ b/app/app/hooks/use-favorites.ts @@ -3,14 +3,20 @@ import { useCallback, useSyncExternalStore } from "react"; const STORAGE_KEY = "favorites"; let listeners: Array<() => void> = []; +let cachedRaw: string | null = null; +let cachedParsed: string[] = []; function getSnapshot(): string[] { try { const raw = localStorage.getItem(STORAGE_KEY); - return raw ? JSON.parse(raw) : []; + if (raw !== cachedRaw) { + cachedRaw = raw; + cachedParsed = raw ? JSON.parse(raw) : []; + } } catch { - return []; + cachedParsed = []; } + return cachedParsed; } function subscribe(cb: () => void) { @@ -20,12 +26,18 @@ function subscribe(cb: () => void) { }; } +const EMPTY: string[] = []; +function getServerSnapshot(): string[] { + return EMPTY; +} + function notify() { + cachedRaw = null; listeners.forEach((l) => l()); } export function useFavorites() { - const favorites = useSyncExternalStore(subscribe, getSnapshot, () => []); + const favorites = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); const isFavorite = useCallback( (id: string) => favorites.includes(id),