简体   繁体   中英

unnecessary re-render reactjs

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 ..

  • 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.

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM