I'm exploring option on how is the most elegant/readable way to pass parameters to a React class method without compromising on performance.
Let's say I have two Arrow
components to switch between items. Each Arrow
listen for click event and trigger a state change on the parent depending on the direction.
The first option is to pass each Arrow
component an arrow function as the onClick
handler with the corresponding direction:
switchItem = dir => {
this.setState(pv => ({ item: (pv.item += dir) }));
};
<Arrow left onClick={() => this.switchItem(-1)} />
<Arrow right onClick={() => this.switchItem(1)} />
This is quite elegant but cause performance issue due to the function being re-created at each render. The same problem apply to currying.
So the second option is to declare a specific handler for each case:
previousItem = () => {
this.setState(pv => ({ item: (pv.item -= 1) }));
};
nextItem = () => {
this.setState(pv => ({ item: (pv.item += 1) }));
};
<Arrow left onClick={this.previousItem} />
<Arrow right onClick={this.nextItem} />
This cause no performance issue but is very verbose and not very reusable (what if we have 10 different arrows with 10 different directions)
Is there other (better) options for doing that ? If not what should be the preferred way ?
Thanks !