What is the difference between these function calling styles?
onPress = { () => { this.myFunctions() } }
And
onPress = { this.myFunctions() }
Difference between passing function and object to setState function State update is done asynchronously in React. So it is important to understand the difference between passing function or object to setState function. Techdomain Tutorials(current) Images Categories About Twitter Difference between passing function and object to setState function
Calling a function says, “go over there to the function definition, do what it says, and come back.” Passing a function says, “use this function as an argument when you do that function call.” How can a function be an argument in a call to another function? Read about “higher order functions” .
Passing a function generally means passing a function as a parameter within another function. This is useful when you want to ensure the function passed is executed after the first one, mostly seen on Javascript Callbacks for asynchronous operations like getting results from an external API or getting info from a database.
It should be noted that form over function doesn't preclude style, it just prioritizes functionality. Much modern architecture is valued for its style. Functionality as the primary goal of an architectural design. Aesthetics as the primary goal of an architectural design.
onPress={() =>{this.myFunctions()}}
You are passing an anonymous function which after onPress was invoked would call this.myFunctions()
onPress={this.myFunctions()}
You are passing into onPress the return value of this.myFunctions
which means this gets executed everytime render is invoked by the component.
Both of the above ways of passing function into a React
component are not advisable performance-wise. Using the above methods causes the function with the onPress to rerender everytime the parent renders because as it does a shallow comparison of previous anonymous function declaration it will result in two function not being equal as it is compared by reference.
It is advised to use below:
onPress={this.myFunctions}
where you are passing the reference of the function myFunctions
. And whenever the parent rerenders, once the component has checked if new myFunctions is the same with previous render, it will return as true and will not render again the child.
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