Reputation: 93
so i have this button to add an item to store u cant add more than one but when i click on the button twice or more it keep re-render two components twice i tried to use useMemo to memorize the value but it wont work and get the (target) from e.target is undefined
const handleAdd = useMemo((e) => {
let newItem = {id : e.target.name, price: e.target.value, title: e.target.title, contity: 1}
item.push(newItem)
const unique = Array.from(new Set(item.map(i => i.id))).map(id =>{return item.find(i => i.id === id)})
setItem(unique)
}),[item])
any solution for useMemo or any other idea to avoid this unnecessary render ..
Upvotes: 0
Views: 107
Reputation: 4519
This could be done without any of these fancy hooks. Here is a great article about when to use useMemo
or useCallback
and why we don't need those most of the time: https://kentcdodds.com/blog/usememo-and-usecallback
Your code could simply check if the item already exists in the array before trying to update it:
const handleAdd = (e) => {
const newId = e.target.name
const itemFound = item.find((i) => i.id === newId)
if (!itemFound) {
const newItem = {id : e.target.name, price: e.target.value, title: e.target.title, contity: 1}
// Using spread to avoid mutability
const updatedItem = [...item, newItem]
setItem(updatedItem)
}
}
Upvotes: 1
Reputation: 121
to handle event's from buttons, inputs etc - use useCallback
hook.
you trigger setItem inside your hook and it causes re-render. Add condition inside your hook and trigger setItem
only when id needed.
Upvotes: 1