Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid anonymous function in react

I have a scenario here

const Parent = () => {
    handleClick = (id) => {
        console.log(id)
    }
    return <div>
        users.map((user, index) => 
        <child key={index} onClick={(user.id)=>handleClick(user.id)} />)
    </div>
}

The child is using React.memo so it won’t re-render unless its props are changed. I don’t want the child to be re-render when the parent renders but in this scenario it will re-render because I am using an anonymous function. I can put handleClick inside of useCallback but how can I avoid the anonymous function here. I have to use an anonymous function here because I am expecting some arguments here.

like image 547
Ahmed Waqas Avatar asked Oct 24 '25 05:10

Ahmed Waqas


2 Answers

You can try using bind.

const Parent = () => {
    handleClick = (id) => {
        console.log(id)
    }
    return <div>
        users.map((user, index) => 
        <Child key={index} onClick={handleClick.bind(this, user.id)} />)
    </div>
}

Here's the relevant section of the React docs: Passing Arguments to Event Handlers

like image 175
Devin Avatar answered Oct 26 '25 19:10

Devin


Although this is an old question, this is the approach I would take (in case it helps somebody else)

  1. Add an attribute to the element, which contains the argument you want to pass as value, e.g id={user.id}
  2. Then just pass the name of the handler in the onClick attribute, and extract the attributes from the event.target in your handler function

NOTE: you don't have to pass the event argument, thus no need to build an anonymous function

const Parent = () => {
  const handleClick = (event) => {
    const {id} = event.target
    console.log(id)
  }
  return users.map((user, index) => 
        <div key={index} id={user.id} onClick={handleClick}>{user.name}</div>)
}
like image 35
JFK Avatar answered Oct 26 '25 18:10

JFK