Skip to content

Commit 2fc60b4

Browse files
committed
[#109] image hook 조금 수정
불필요한 리랜더링 방지.
1 parent 5b65bd4 commit 2fc60b4

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

src/hooks/use-image-loader.jsx

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,36 +29,51 @@ function useImageListLodeChecker(imageList = []) {
2929
useEffect(() => {
3030
if (!imageList.length) return;
3131

32+
let cancelled = false;
33+
3234
setImageLoadStates((prev) => {
3335
const nextStates = { ...prev };
3436
imageList.forEach(({ id }) => {
35-
if (nextStates[id] === undefined) {
36-
nextStates[id] = false;
37-
}
37+
if (nextStates[id] === undefined) nextStates[id] = false;
3838
});
3939
return nextStates;
4040
});
4141

42+
const imageMap = {};
43+
4244
imageList.forEach(({ id, backgroundImageURL }) => {
4345
setImageLoadStates((prev) => {
44-
if (prev[id]) return prev;
46+
if (prev[id] === true) return prev;
4547

46-
if (!backgroundImageURL) {
47-
return { ...prev, [id]: false };
48-
}
48+
if (!backgroundImageURL) return { ...prev, [id]: false };
4949

5050
const img = new Image();
51+
imageMap[id] = img;
52+
5153
img.onload = () => {
52-
setImageLoadStates((p) => ({ ...p, [id]: true }));
54+
if (!cancelled) {
55+
setImageLoadStates((p) => ({ ...p, [id]: true }));
56+
}
5357
};
58+
5459
img.onerror = () => {
55-
setImageLoadStates((p) => ({ ...p, [id]: false }));
60+
if (!cancelled) {
61+
setImageLoadStates((p) => ({ ...p, [id]: false }));
62+
}
5663
};
57-
img.src = backgroundImageURL;
5864

65+
img.src = backgroundImageURL;
5966
return prev;
6067
});
6168
});
69+
70+
return () => {
71+
cancelled = true;
72+
Object.values(imageMap).forEach((img) => {
73+
img.onload = null;
74+
img.onerror = null;
75+
});
76+
};
6277
}, [imageList]);
6378

6479
return imageLoadStates;

0 commit comments

Comments
 (0)