If you’re a junior/mid-level developer, usually you don’t care too much about performance at the beginning when you’re creating a ReactJS component, that’s why I just want to put on the table this topic in order to improve your code since the first lines of code.
What is useCallback?
First we have to define this concept if you’re not familiar with the it,
useCallback is a ReactJS Hook, if you want to go deeper go here.
What is useCallback for?
I can’t get a better explanation rather than the official one:
Let’s dive into the syntax
but first, if you’re not familiar with the expression
memoized , let’s just say that is a technique to speed up expensive processes, I’ll explain this more in a bit.
So, the code above is the syntax, a function that receives a function and an array of inputs or dependencies.
Let’s explain what we’ll get, as you might guess, the outcome of the function is a
memoized version of the first parameter (the function) and during the lifecycle of the component you’ll get the same cached reference to the function at least until the input
b changed. In other words, if
b changes, you’ll get a new version of the function, this enables you to have a optimized component because you’re not allocating a new function (the annonymous function which has the`doSomething()` call), every time the component renders.
What if you pass an empty array as second parameter?
That’s easy, you’ll get a single and unique reference to the function that it’s going to be ready as soon as the component is created, and it’ll keep the same reference during the lifecycle of the component.
Wrap it up
Just be aware that every function is not suitable for
useCallback , this is not a silver bullet, keep in mind all the inputs or dependencies you have; this hook could become a good friend but also a pain in the butt.