Skip to content

Instantly share code, notes, and snippets.

@creotip
Created July 7, 2021 15:58
Show Gist options
  • Save creotip/335a18787555242950c40f25746acf39 to your computer and use it in GitHub Desktop.
Save creotip/335a18787555242950c40f25746acf39 to your computer and use it in GitHub Desktop.
React: Prevent re-rendering of a list, while removing an item
import React, { useState, useCallback } from "react";
const todos = [
{
name: "TODO Task No.0",
id: 8598554
},
{
name: "TODO Task No.1",
id: 189730
},
{
name: "TODO Task No.2",
id: 609396
},
{
name: "TODO Task No.3",
id: 1927856
},
{
name: "TODO Task No.4",
id: 4070713
}
];
const Item = React.memo(({ id, name, handleDelete }) => {
console.log("Render Item: ", id);
return (
<div
onClick={() => handleDelete(id)}
title="Click to delete"
style={{ padding: "1rem", border: "1px solid", cursor: "pointer" }}
>
<div>
<div>{name}</div>
<div>ID: {id}</div>
</div>
</div>
);
});
const App = () => {
const [newItems, setNewItems] = useState(todos);
const handleDelete = useCallback((id) => {
setNewItems((newItems) => newItems.filter((item) => item.id !== id));
}, []);
return (
<div className="appList">
{newItems.map((item, i) => (
<Item key={item.id} {...item} handleDelete={handleDelete} />
))}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment