From 4e0692c6bcd4ef25b02feffbebe5d2e5e6e50268 Mon Sep 17 00:00:00 2001 From: surya0904shankar Date: Sun, 5 Jul 2026 19:57:11 +0530 Subject: [PATCH] perf(render): fix stale closure in togglePin to complete memoization work Closes #1458 --- src/components/TopRepos.tsx | 52 +++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/src/components/TopRepos.tsx b/src/components/TopRepos.tsx index baacc0268..696e9e7f0 100644 --- a/src/components/TopRepos.tsx +++ b/src/components/TopRepos.tsx @@ -324,39 +324,41 @@ export default function TopRepos() { ); }, []); - const togglePin = async (repoFullName: string) => { - const isPinned = pinnedRepos.includes(repoFullName); - let newPinsArray: string[]; - - if (isPinned) { - newPinsArray = pinnedRepos.filter(name => name !== repoFullName); - } else { - if (pinnedRepos.length >= 3) { - setPinError("Maximum 3 pins allowed"); - return; - } - newPinsArray = [...pinnedRepos, repoFullName]; - } - +const togglePin = useCallback((repoFullName: string) => { setPinError(null); - const prevPins = [...pinnedRepos]; - setPinnedRepos(newPinsArray); + setPinnedRepos((prevPins) => { + const isPinned = prevPins.includes(repoFullName); + let newPinsArray: string[]; + + if (isPinned) { + newPinsArray = prevPins.filter((name) => name !== repoFullName); + } else { + if (prevPins.length >= 3) { + setPinError("Maximum 3 pins allowed"); + return prevPins; + } + newPinsArray = [...prevPins, repoFullName]; + } - try { - const res = await fetch("/api/user/settings", { + fetch("/api/user/settings", { method: "PATCH", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ pinned_repos: newPinsArray }), - }); - if (!res.ok) throw new Error("Failed to update pins"); - } catch (err) { - console.error(err); - setPinnedRepos(prevPins); - } - }; + }) + .then((res) => { + if (!res.ok) throw new Error("Failed to update pins"); + }) + .catch((err) => { + console.error(err); + setPinnedRepos(prevPins); + }); + + return newPinsArray; + }); + }, []); const fetchRepos = useCallback(() => { setLoading(true);