A higher-order function is a function that returns a new function. Sometimes, higher-order functions take functions as arguments too. In the preceding example, you used bind() to bind the context and argument values of your event handler functions. Higher-order functions that return event handler functions are another technique. The main advantage of this technique is that you don't call bind() several times. Instead, you just call the function where you want to bind parameters to the function. Let's look at an example component:
import React, { Fragment, Component } from 'react';
export default class App extends Component {
state = {
first: 0,
second: 0,
third: 0
};
// This function is defined as an arrow function, so "this" is
// lexically-bound to this component. The name argument is used
// by the function that's returned as the event handler in the
// computed property name.
onClick = name => () => {
this.setState(state => ({
...state,
[name]: state[name] + 1
}));
};
render() {
const { first, second, third } = this.state;
return (
<Fragment>
{/* By calling this.onClick() and supplying an argument value,
you're creating a new event handler function on the fly.
*/}
<button onClick={this.onClick('first')}>First {first}</button>
<button onClick={this.onClick('second')}>
Second {second}
</button>
<button onClick={this.onClick('third')}>Third {third}</button>
</Fragment>
);
}
}
This component renders three buttons and has three pieces of stateāa counter for each button. The onClick() function is automatically bound to the component context because it's defined as an arrow function. It takes a name argument and returns a new function. The function that is returned uses this name value when called. It uses computed property syntax (variables inside []) to increment the state value for the given name. Here's what that component content looks like after each button has been clicked a few times:
