useCallback
Last updated
Was this helpful?
Last updated
Was this helpful?
The useCallback
hook is used to avoid re-creating functions during every execution of the hook. That helps to reduce the need to rebind event handlers and to create a more stable API from your own hooks.
useCallback(callbackFunction: Function, cacheKeyProperties: Array<Any>): Function
useCallback
accepts a function and, , an array of cache keys which determine when to re-create the callback.
In the example above the callback will always be the same as long as the handleClick
property stays the same. We express that dependency by including it in the cacheKeyProperties
array.
As a consequence, Melody will only need to attach and remove the event handler when handleClick
is changed.
Since hooks are generally a very new concept and lots of material is being written about them, there's also a very high chance that you'll face some very bad examples.
In that example the callback depends on the toggled state. Thus, every time the user actually toggles the button, the callback will need to be re-created.
How to avoid: Reduce dependencies as much as you can. Any dependency that is not strictly necessary is a dependency too much.
Given an empty array, useCallback
will always return the very first function it has ever received. That's the ideal case that you should always try to achieve. The as well as can help you achieve this goal. However, sometimes, like in the previous use case, you will need to rebind because of changing event handlers. That can be avoided by embracing the platform more strongly and by using the native event dispatching mechanism instead.