fix: prevent race conditions and memory leaks in useCommentMediaInfo hook

This commit is contained in:
plebeius
2025-10-16 23:27:06 +02:00
parent 55c7e685d6
commit fc4802186d
+28 -4
View File
@@ -19,26 +19,50 @@ export const useCommentMediaInfo = (link: string, thumbnailUrl: string, linkWidt
useEffect(() => { useEffect(() => {
if (!(isInPostPageView || isInPendingPostView)) return; if (!(isInPostPageView || isInPendingPostView)) return;
// Reset dimensions when inputs change to avoid stale state
setThumbnailDimensions(null);
let isMounted = true;
let img: HTMLImageElement | null = null;
const fetchAndCacheThumbnail = async () => { const fetchAndCacheThumbnail = async () => {
const mediaInfo = getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const mediaInfo = getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight);
if (mediaInfo?.type === 'webpage' && !mediaInfo.thumbnail) { if (mediaInfo?.type === 'webpage' && !mediaInfo.thumbnail) {
const newMediaInfo = await fetchWebpageThumbnailIfNeeded(mediaInfo); const newMediaInfo = await fetchWebpageThumbnailIfNeeded(mediaInfo);
if (newMediaInfo.thumbnail) { if (newMediaInfo.thumbnail && isMounted) {
const img = new Image(); img = new Image();
img.onload = () => {
const handleLoad = () => {
// Only update state if component is still mounted and this is the latest request
if (isMounted && img) {
setThumbnailDimensions({ width: img.width, height: img.height }); setThumbnailDimensions({ width: img.width, height: img.height });
}
}; };
img.onerror = () => {
const handleError = () => {
// Silently handle failed image loads // Silently handle failed image loads
}; };
img.onload = handleLoad;
img.onerror = handleError;
img.src = newMediaInfo.thumbnail; img.src = newMediaInfo.thumbnail;
} }
} }
}; };
fetchAndCacheThumbnail(); fetchAndCacheThumbnail();
// Cleanup function to prevent memory leaks and race conditions
return () => {
isMounted = false;
if (img) {
// Remove event handlers to prevent them from being called after cleanup
img.onload = null;
img.onerror = null;
}
};
}, [link, thumbnailUrl, linkWidth, linkHeight, isInPostPageView, isInPendingPostView]); }, [link, thumbnailUrl, linkWidth, linkHeight, isInPostPageView, isInPendingPostView]);
const mediaInfo = getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight); const mediaInfo = getCommentMediaInfo(link, thumbnailUrl, linkWidth, linkHeight);