How hook useCallback works?

What is useCallback in React JS?
UseCallback is a native React JS hook that memorizes functions, preventing them from being recreated every time a component is rendered, unless there's a change in the dependency list.
Let's explain with simple examples.
Imagine you need to bake a cake. To do so, you'll need a recipe. Imagine that every time you bake the cake, you'll need to rewrite the recipe. We don't need that, right? If we always have the ingredient list, we'll only need to change it if the ingredients change.
In our case, the ingredients are our dependency list, and the recipe is our function. We only need to rewrite the function (our cake recipe) if any item in our dependency list changes.
Hook sintaxe
useCallback has a simple syntax, very similar to the useMemo hook.
syntax: useCallback(fn, dependencies)
- Fn: This is the function you need to cache. On the initial render, React will return your function but not call it. On subsequent renders, React will return the exact same function (the one stored) if nothing in the dependency list changes.
- dependencies: These are the properties, states, or any functions or variables declared in the body of your component. When the value of a dependency changes, the function (fn) will be written and cached again.
const helloWordFunction = useCallback(()=>
console.log(helloWord!), //calback function
[var1, var2]) //dependency array
useCallback example
Based on the illustration above, let's see the difference between a component with the useCallback hook and one without it.
Example: Making a carrot cake without useCallback. In this example, we have two options for making the same cake:
1 — Using the useCallback hook: We'll use the same recipe every time the button to make a cake is clicked. If any item in the ingredient list changes, we'll write the recipe again and make the cake.
2 — Without the useCallback hook: We'll write the recipe again every time the button to make a cake is clicked.
You can see that if you choose the second option, in the console, you'll see that the child component is re-rendered every time the button is clicked.
Instead, if you use the first option, the function will be remembered and only the function's log will appear in the console, showing that the child component was not re-rendered.
Subscribe to my newsletter
Read articles from Jonatas Artagnan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
