How to avoid anonymous function in react

Viewed 1306

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.

1 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

Related