UseMemo & UseCallback

UseMemo & UseCallback

ยท

1 min read

I kept myself busy tonight by studying more about useMemo and useCallback, two React hooks used to improve the app's performance.

Why using them?

First of all, we should know that in React for every DOM object there is a corresponding Virtual DOM object.

Since manipulating the DOM is slow, in React we manipulate the Virtual DOM which is much faster. It then gets compared to the real DOM, and React can find any difference an update the relevant parts.

However, sometimes this is not enough,so we need to prevent React from re-rendering expensive functions or components.

This is where useMemo and useCallback come into play!

The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value, and useCallback returns a memoized function. They both accept an array of dependencies as a second value (much like useEffect) if we want to tell React when to run a re-render.

Here you can look at a simple test I made: Github link

Or check out some code examples from Dmitri Pavlutin website: Dmitri Pavlutin

ย