What is useCallback hook in React?

Subscribe to my newsletter and never miss my upcoming articles

New post in the React series about the useCallback hook. Everything you need to know.

What is useCallback?

Do you remember the useMemo hook which we saw in the last post? The useCallback hook is also very similar and it returns a memoized callback.

The useCallback hook is very useful in dealing with referential equality situations to prevent unnecessary renders.

Let's understand this in a good way:

Consider a case where we have to maintain two counters inside a single component. Each counter has its independent control.

Now, even if you increment one counter, the other one will rerender(because they are in the same component).

This may not be an issue in the case of a simple counter, however. if it is a slow and expensive function, you would want to avoid this.

How to use the useCallback hook?

The ideal solution in the previous case is that, if the state value of the other counter remains unchanged then it should not be rendered.

// Counter 1 -> If you increment this, the other counter function will be recreated. // Counter 2 -> Similarly, if you increment this, the whole component will rerender and the other counter function will be recreated.

So to fix this issue, can wrap both the counter functions in a useCallback. The only when the state is changed the function will be recreated.


const memoizedCallback - useCallback(
    () => {
        doSomething(a, b); //Memoized callback function
    [a, b], //Dependency array: The function will rerun only if any of the value from this array changes.

The concept of remembering the function so that we don't have to recreate it on every render is known as Memoization.

As we saw in the last post that we already have useMemo hook for this. When why is useCallback even required?

When to use the useCallback hook?

The major difference between useMemo and useCallback is that useMemo returns a memoized value, whereas useCallback returns a memoized function.

So if your memoized function is receiving some external parameters and performing some calculation based on that, then it makes sense to use the useCallback hook.

However, if you are only concerned about the memoized value, then probably useMemo is the best option.


However, there are situations when rendering can take a substantial amount of time (think highly interactive Graphs/ Charts/ Animations). Thanks to the pragmatic nature of React, there's an escape hatch via useMemo and useCallback.

😎Thanks For Reading | Happy Coding ⚡

No Comments Yet