How to pass arguments to callback in React + Typescript without new function creation?

Viewed 4380

Say you have the following TSX code:

render() {
    const someParameter = 5;

    return (
        <div onClick={() => this.doSomething(someParameter)}></div>
    );
}

Now, we know that we shouldn't pass fat arrow functions like this to the onClick handler because it will create a new function every time, forcing a rerender (this is especially bad when we're passing this callback to a deep component, not just a div).

So then the solution, if there were no parameters, would be to bind doSomething to this in the constructor of our class, like this.doSomething = this.doSomething.bind(this) and then pass the bound function as the callback. However, this doesn't cut it in our case, because we want to pass a parameter to the function - someParameter. Imagine that someParameter wasn't just a stupid constant like it is above, but instead an element in an array that we get in a map() over an array in our render method. How do we handle this situation? That is, how do we pass a function that is not created from scratch every time, thereby breaking our ability to smartly rerender only when necessary?

Thanks!

2 Answers
Related