Understanding useCallback

Raazesh Prajapati
readytowork, Inc.
Published in
2 min readSep 12, 2022

The useCallback hook is exactly similar to useMemo, the only difference is that it returns a memoized callback instead of memoized value when passed a function and a list of dependencies as parameters. It’s very useful when a component is passing a callback to its child component to prevent the rendering of the child component. It only changes the callback when one of its dependencies gets changed.

Syntax:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Function in javascript is just a regular object, so the function is also called first-class citizen in javascript. So same as Object and array, two Functions in javascript are not exactly equal even though they share the same code and same value which have been discussed as Referential Equality in my article on useMemo .

Let us see the useCallback function through the example:

Here we are creating a simple react child component Todo.

Now, let us use our Todo component in our application as a child component.

Issue:

Our Todo component re-render, although our Todo component is independent of the + button should be avoided to increase the performance of our application.

Here the issue is that the child component should be rendered only when Add todo is clicked. But it is re-rendering whenever + is clicked.

Solution:

Above re-rendering of the component can be solved with the help of Memo and useCallback hooks of react.

Firstly, we should wrap our child component with memo HOC as shown below:

And now, let's move to our parent component code and optimize our application.

Here, we wrap out the addTodo function with useCallback hooks and pass the todos array as the dependency.

Here, we can see that our Todo child component only re-renders on clicking Add Todo button and avoid re-rendering on the click+ button which is our objective. This helps us to improve our performance in our application.

Conclusion

Hence we conclude to use useCallback hooks whenever we need to avoid expensive calculations and unnecessary re-rendering of child components to enhance and optimize our react application performance.

Thank you!!!

--

--