How can I bind function with hooks in React?
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
class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <Button onClick={this.handleClick}>Click Me</Button>;
}
}
Hooks
function Foo() {
const memoizedHandleClick = useCallback(
() => {
console.log('Click happened');
},
[], // Tells React to memoize regardless of arguments.
);
return <Button onClick={memoizedHandleClick}>Click Me</Button>;
}
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
function Foo() {
const handleClick = function(){
// use function statements to avoid creating new instances on every render
// when you use `bind` or arrow functions
console.log('memoizing can lead to more work!')
};
return <Button onClick={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.