I have recently started to use hooks and was migrating existing class components to hooks. Amidst several perf benefits of using hooks, one aspect which I could not grasp was how callbacks are passed.
Hooks introduces useCallback which provides a memoized callback so that every re-render need not unnecessarily generate a new method. But still upon going through the API's setup, I can see that for every render it still does a lot.
Class API on the other hand provides a simple way of binding a callback once and hence there would not be any additional mixins for every render.
Sample code for comparison :
/**
* Hooks
*/
function Test() {
const handleCallback = React.useCallback(() => {
/**
* Callback handler implementation
*/
}, [/** deps */]);
return <ChildComponent callback={handleCallback} />;
}
/**
* Class API
*/
class Test extends React.Component {
handleCallback = () => {
/**
* Callback handler implementation
*/
};
render() {
return <ChildComponent callback={this.handleCallback} />;
}
}
Quoting from docs:
Hooks let you organize side effects in a component by what pieces are related (such as adding and removing a subscription), rather than forcing a split based on lifecycle methods.
Is this perf hit the expected tradeoff of having all pieces in one place ?
Would there be any scenario where you would use an inline callback as it would always result in re-render of children. In that case isn't
useCallbackalmost always needed ?