Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between style of passing functions

What is the difference between these function calling styles?

onPress = { () => { this.myFunctions() } }

And

onPress = { this.myFunctions() }
like image 925
Nguyễn Tuấn Vũ Avatar asked Mar 18 '19 02:03

Nguyễn Tuấn Vũ


People also ask

What is diff between passing function and object to setState function?

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

What is the difference between calling a function and passing it?

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” .

What does it mean to pass a function as a parameter?

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.

What is the difference between form over function and style?

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.


1 Answers

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.

like image 118
Jojo Narte Avatar answered Sep 27 '22 19:09

Jojo Narte