Reactor shutdown

Is it good to use closures in reactions for event handlers? For example, I have a function and a lot of menus in the navigation and in the navigation component I use something like this:

handleMenuClick(path) { return () => router.goTo(path) } ... <MenuItem handleTouchTap={this.handleMenuClick('/home')} > 

Or should I only prefer the arrow function?

 <MenuItem handleTouchTap={() => router.goTo('/home')} > 

the first option really makes the code cleaner, but I'm worried about performance with a lot of such elements

+5
source share
2 answers

Both should be avoided.

While both of them work, they have the same weakness that they will cause unnecessary visualizations, because the function is created dynamically and, thus, will be presented as another object.

Instead of any of them, you want to create your functions in a static way and then pass them. For something like your MenuItem , it should just get a string for the path, and then make code to do the routing inside. If he needs a router, you should pass this instead.

Then the function should be a preliminary bind -ed function (usually in the constructor) and simply passed.

 export class MenuItem extends React.Component { constructor() { this.handleClick = () => this.props.router.go(this.props.path); } render() { return ( <Button onClick={ this.handleClick }>Go to link</Button> ); } } 

You can use the arrow function in the constructor. This way, it is not recreated by every rendering function, and therefore you avoid unnecessary renderings. This template works well for simple simple simple functions. For more complex functions, you can also create them as a separate function, and then bind in the constructor.

 export class MenuItem extends React.Component { handleClick() { this.props.router.go(this.props.path); } constructor() { this.handleClick = this.handleClick.bind(this); } render() { /* same as above */ } } 

The fact is that a handler is the same function every time. If it were different (which both methods described above would be), then React will do unnecessary re-renderings of the object, because each time it will be a different function.

Here are two articles that are provided in more detail:

+7
source

when you define a new method inside the responsive component (Object), since we know that functions are objects in javascript.

  let reactComponent={ addition: function(){ //some task ...}, render: function(){}, componentWillMount : function(){}, } 

therefore, each new method must be associated with the object using bind, but render () is already defined, so we do not

 this.render = this.render.bind(this) 

for each new function, except that it is necessary to use life cycle methods, and therefore, we call methods of the object (constructor) using this.method ().

0
source

Source: https://habr.com/ru/post/1269724/


All Articles