How Can I Bind Function With Hooks In React?
Solution 1:
There's no need to bind functions/callbacks in functional components since there's no this
in functions. In classes, it was important to bind this
because we want to ensure that the this
in the callbacks referred to the component's instance itself. However, doing .bind
in the constructor has another useful property of creating the functions once during the entire lifecycle of the component and a new callback wasn't created in every call of render()
. To do only initialize the callback once using React hooks, you would use useCallback
.
Classes
classFooextendsComponent {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return<ButtononClick={this.handleClick}>Click Me</Button>;
}
}
Hooks
functionFoo() {
const memoizedHandleClick = useCallback(
() => {
console.log('Click happened');
},
[], // Tells React to memoize regardless of arguments.
);
return<ButtononClick={memoizedHandleClick}>Click Me</Button>;
}
Solution 2:
People come to SO and copy-paste code. Leaving this answer here, so the React community doesn't go around incorrectly memoizing everything and potentially doing more work than necessary.
Function components
functionFoo() {
const handleClick = function(){
// use function statements to avoid creating new instances on every render// when you use `bind` or arrow functionsconsole.log('memoizing can lead to more work!')
};
return<ButtononClick={handleClick}>Click Me</Button>;
}
Tip: look at what code is transpiled when using useCallback
and see if it's necessary, before dropping it in. if you're not sure you need it, you probably don't. and to be sure it's doing you good, profile it.
Solution 3:
You might as well write the component Foo
above like this and save yourself some typing. Note the syntax around handleClick ... it defines the closure handleClick as a field on Foo, rather than as a method. This removes the need for you to use bind to overwrite the OBject's 'handleClick' reference in the constructor. (Also, you don't need to define a constructor if you're just calling 'super'!)
classFooextendsComponent {
handleClick = () => {
console.log('Click happened');
}
render() {
return<ButtononClick={this.handleClick}>Click Me</Button>;
}
}
Similarly, for your original example, just declare state and setCount directly and to simplify your code:
classTestextendsComponent{
state = {count: 0}
setCount = () => {
this.setState({count: this.state.count + 1});
}
render() {
return<buttononClick={this.setCount}>Increase</button>
}
}
Post a Comment for "How Can I Bind Function With Hooks In React?"