Go Back to Blogs

Please, useCallback

Please, useCallback: is rerendering again and again without need.

Julián Alzate

Frontend Developer
September 28, 2021
an image of a right pointing down to go to an specific section of the current page.

Please, useCallback

Optimizing ReactJS with useCallback

For junior or mid-level developers diving into the world of ReactJS, performance might not be the initial priority. However, it's essential to weave in efficiency from the get-go. Enter the concept of useCallback.

Understanding useCallback

If you're scratching your head about what useCallback is, let's break it down. At its core, useCallback is a ReactJS Hook. For a deeper dive, follow the link provided (not included in this rendition).

The official explanation aptly encapsulates its essence, but let's make it even clearer:

Deciphering Memoization

Before we delve deeper, let's address the term memoized. Think of it as a technique to fast-track processes that are resource-intensive.

Syntax and Application

The given code illustrates the syntax: it's a function taking another function and an array of inputs (or dependencies).

What's the catch? The result is a memoized version of the initial function. Throughout the component's lifecycle, this cached reference remains consistent, unless the inputs (like a or b) change. So, if either input is altered, a new function version is generated. The magic lies in the optimization: instead of constantly allocating a new function (the anonymous function with the doSomething() call) with each component render, the component retains the memoized function.

In simpler terms, this hook ensures that the component starts with a unique function reference that remains constant during its lifecycle.

A Word of Caution

useCallback isn’t a cure-all solution. Not every function is a candidate for it. It’s paramount to recognize your function's inputs or dependencies. While useCallback can be a developer's boon, misuse might make it more of a burden.

Written by Julián Alzate

We Love Hearing from You!

Interested in getting started with us and taking your company to the next level?
Achieve your goals today!
our coworker gustavo posing