Photo by Daniel Eledut on Unsplash

REACT PERFORMANCE

Analyses on Re-render of React Components — 2 (useCallback)

Several methods are used to obtain a performance out of the normal rendering logic of the React components. In this article, we will analyze the use of React.Memo and the useCallback.

React Digital Garden
3 min readOct 8, 2022

--

In the first article (Analyses-1), I have focused on the methods that can be used over the state and props changes on the Class Components. In this article, I will explain the use of useCallback and useMemo which I mentioned within the React Hooks.

useCallback ve useMemo

Let’s a little change the logic in the first scenario. We have made memoization with the same Hook Component React.Memo. But this time we implement a callback function in it. (Sample implementation)

We realize 3 different types of callback implementation.

  • Defining a const callback and implementing this on the sub-component as a props
  • Implementing the props callback function to the component as inline
  • Lastly, implementing the function to the component by using the useCallback

Let’s increase the counter on the parent component to see which of them are rendered.

Although we use React.memo, when the update in the parent component starts to trigger the sub-components and we cover the callback with only useCallback, the child component does not render itself. Why?

The reason is the React.memo, if we do not give any check action, if we do not make the following props comparison,

React compares this shallowly, that is it compares the props parameters with ===.

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

Then (===) while this is useful in primitive types I explained in JS Data Types, it will make a comparison over the reference in the others.

In this case, as we implement a new callback to the component during each render, how can we make the references same?

Here, the useCallback hook intervenes. It is allowed to use the same reference as long as the [a, b] within the dependency array in this callback does not change.

https://reactjs.org/docs/hooks-reference.html#usecallback

References

--

--