Skip to content

Commit c7b16cb

Browse files
committed
Refactor Bookmarks component to use useCallback for bookmark removal and optimize rendering logic
1 parent 5ba2c3b commit c7b16cb

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

‎src/pages/Bookmarks.jsx‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,41 @@
1-
import React, { useState } from "react";
1+
import React, { useState, useCallback } from "react";
22
import { useGlobalContext } from "../Context";
33

44
const Bookmarks = () => {
55
const { bookMark, setBookMark } = useGlobalContext();
66
const [removingId, setRemovingId] = useState(null);
77

8-
if (!bookMark.length) {
9-
return (
10-
<div style={{ display: "grid", placeItems: "center", height: "100vh" }}>
11-
<h1>No Bookmarks Yet! ⭐</h1>
12-
</div>
13-
);
14-
}
15-
16-
const removeBookmark = (news) => {
17-
setRemovingId(news.objectID);
8+
const removeBookmark = useCallback((news) => {
9+
setRemovingId(news.objectID);
1810

1911
setTimeout(() => {
2012
const updatedBookmarks = bookMark.filter(
2113
(item) => item.objectID !== news.objectID
2214
);
2315
setBookMark(updatedBookmarks);
2416
localStorage.setItem("bookmarks", JSON.stringify(updatedBookmarks));
25-
}, 300);
26-
};
17+
setRemovingId(null);
18+
}, 300);
19+
}, [bookMark, setBookMark]);
20+
21+
if (!bookMark.length) {
22+
return (
23+
<div style={{ display: "grid", placeItems: "center", height: "100vh" }}>
24+
<h1>No Bookmarks Yet! ⭐</h1>
25+
</div>
26+
);
27+
}
2728

2829
return (
2930
<>
3031
<div className="stories-div" style={{ paddingTop: "3rem" }}>
3132
{bookMark.map((curPost) => {
3233
const { title, author, objectID, url, num_comments } = curPost;
34+
const isRemoving = removingId === objectID;
35+
3336
return (
3437
<div
35-
className={`card ${removingId === objectID ? "removing" : ""}`}
38+
className={`card ${isRemoving ? "removing" : ""}`}
3639
key={objectID}
3740
>
3841
<h2>{title}</h2>

0 commit comments

Comments
 (0)