Improve your React app performance with "useCallbak" Hook
UseCallback is a hook that allows us to store a function across component executions.
UseCallback tells React to save a function somewhere in React's internal storage and not to be recreated with every execution, so we will always reuse that same function object
When to use?
In case your function has always the same logic across rerender cycles, for example, the “toggleHandler” function in the below screenshot, should not be changed. In other words, no need to recreate the “toggleHandler” function on every execution, in this case we can use the “useCallback” hook
The App component is calling the "Btn" component, where the "toggleHandler" function is called on every button click.
How to use ?
We have to wrap the function that we want to save with useCallback. useCallback has two arguments:
Now when the app function reruns, the “UseCallback” will look for that stored function which React stored for us and reuse that same function object.
See the difference :
Before using the useCallback hook:
we can see in the logs that on every button click , the component is re executing
After using the useCallback hook:
we can see in the logs that no execution is being done after the first click.
In simple apps, this may not matter. Nonetheless, in bigger apps, you might want to optimize that, since this may leads to ongoing function executions that certainly costs some performance.