In react native when you have functions that need to run at render and must pass variables, most people suggest that one should use
onPress{() => this.functionName(variable)}
However when working with large lists and complex components you have to optimize your code. Creating a new function for every renderItem in a flatList
reduces performance, sometimes hugely so depending on how many functions per renderItem you are creating. So the suggestion is to move from creating a function at render to using a function reference. Like this:
functionName = () => {
//code
}
onPress={this.functionName}
However I haven't been able to figure out how to pass variables to the function with this method.
If you do this:
onPress={this.functionName(variable}
It will just run the function instantly on component load.
Any ideas?
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
You can do it either way. Put an '&' symbol in front and the variable you are passing becomes one and the same as its origin i.e. you can pass by reference, rather than make a copy of it.
Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.
I highly recommend using currying to pass an argument.
Currying is the process in which you separate a function into several functions that each take a single argument. The reason why this method works really well, in this case, is because when you call a function on the render method, the argument passed is automatically the event
, so to pass the second argument, the function would have to be curried in order receive the next argument.
You would define your function as such:
functionName = variable => event => {
//code
}
You can then go ahead and call your function in the render method:
onPress={this.functionName(variable)}
This is a great article if you would like to learn more: Currying In JS
This method is extremely elegant and useful because it removes the need to wrap your function call in an anonymous function inside the render method of React.
In any other case, you can also do what the official React Docs suggest: React Docs on passing arguments to event handlers
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With