Improve your React app performance with "useCallbak"? Hook

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

No alt text provided for this image

The App component is calling the "Btn" component, where the "toggleHandler" function is called on every button click.

No alt text provided for this image


How to use ?

We have to wrap the function that we want to save with useCallback. useCallback has two arguments:

  • First argument : our function to use callback
  • ?Second argument: should be an array of dependencies of this call back

No alt text provided for this image

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 :

No alt text provided for this image

Before using the useCallback hook:

we can see in the logs that on every button click , the component is re executing



No alt text provided for this image

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.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了