react-hook

React-Hook : Difference between useCallback and useMemo

Spread the love

Many React developers may feel quilt confused about the difference between useCallback and useMemo hooks. What is the difference between useCallBack and useMemo? And why do useMemo and useCallback expect a function? If you’ve worked with React Hooks, you might have asked yourself these questions.

We will take a look at how they are different from another.

useCallback returns a memoized callback and on the other hand, useMemo returns a memoized value.

What are React-Hooks?

Hooks basically are a new feature introduced in React 16.8; it allows the useState , useEffect, and other React features without writing a single class. Hooks are methods and functions that can “hook into” React’s state and lifecycle features. It doesn’t work inside class components.

What is useCallback?

The useCallback hook is used when a child component is rerendering over and over again without any need. By using useCallback, you can prevent unnecessarily re-rendering components by returning the same instance of the function that is passed instead of creating a new one each time.

Syntax of useCallback: 

const memoizedCallback = useCallback(() => {
   doSomething(a, b);
}, [a,b])

What is useMemo?

The useMemo hook is used in the functional component of React to return a memoized value. memoization is a concept used in general when we can save re-compilation time by returning the cached result. In the functional components of React, useMemo hooks provide memory-mapped values.

Now, you must be wondering what memoization is in React-Hooks.

Memoization:

Memoization refers to the concept of not recompiling a function with the same argument again for the next run because it returns the cached result the next time that it is called.

Syntax of useMemo:

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

At first glance, it might look like useCallback and useMemo usage are quite similar, however, it’s not. Therefore, there are many chances to get confused about when to utilize useCallback and useMemo. 

Difference Between useMemo And useCallback:

In both useMemo and useCallback, the hook accepts a function and an array of dependencies. The major difference between useCallback and useMemo is that useCallback will memory the returned value, whereas useMemo will memory the function. Essentially, the only difference between these hooks is that one cache a value type, and the other caches a function.

Let’s take an example; if the computationally expensive code accepts arguments and returns a value, you would need to use useMemo so you could keep referencing that value between renders without re-running the computationally expensive code.

On the other hand, in order to keep a function instance persistent for multiple renders, useCallback is needed. This is like placing a function outside the scope of your react component to keep it intact.

28 thoughts on “React-Hook : Difference between useCallback and useMemo

  1. Доброго времени суток, если вы планировали взять займ тогда приглашаем вас на сайт Mikro-Zaim-Online.ru где вы найдете всю подробную информацию и конечно список лучших микрофинансовых компаний.

    Для вас мы подобрали проверенные МФО И МФК 2022 где вы узнаете все подробности про займы на карту онлайн где лучше брать и как правильно заполнять заявку чтобы получить 100% одобрение под низкий процент!

    Еще у нас есть раздел с компаниями которые проводят акцию в виде “займы без процентов для новых клиентов” обычно на сумму до 15 000 рублей и сроком от 7 до 30 дней, это очень хороший вариант занять денег и не переплачивая проценты улучшить свою кредитную историю.

Leave a Reply

Your email address will not be published.