Part 4 of the ReactHooks series! We're going to talk about useCallback and useMemo. With these hooks we can memoize values or callbacks, which can be useful for heavy operations or to ensure that certain components do not always render. Especially because with small applications it is often more efficient not to optimize than to optimize.
When I started the first article I had no idea it was going to be a whole series and certainly not one that would get this big, but we have now arrived at part 4 of React Hooks. Below you can see the previous installments of the series. In this article we are going to talk about the useCallback and useMemo hook and when to use them.
useCallback and useMemo are 2 hooks that both use memoization. Memoization is an optimization technique to make programs run faster. It can save the result of function calls and cache them and as soon as the same input is entered again it returns it immediately instead of executing the function again. useCallback returns a memoized callback and useMemo returns a memoized value.
useCallback
If we look at the official documentation of React they say useCallback returned a memoized callback. useCallback returns a memoized version of the callback that only changes if one of its dependencies changes. Well you could say that you are going to put every function in a useCallback, but every optimization brings dangers and in many cases it also makes it slower instead of faster.
const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], );
That's why you have to think carefully about where you can and where you can't use useCallback. An example could be if you keep 3 different counters in your App.js then you don't want that when the state of one of the counters is updated that all functions return only those that depend on that specific counter. Well in most cases this is not a problem because the creation of such a function is negligible and useCallback makes your application slower rather than faster. But if you pass on a lot of large functions that are quite large, useCallback can help you.
useMemo
Just like use callback, useMemo also uses memoization, only in this case no callback is moized but values. For example, if you have a very heavy calculation, you can memoize the result so that you don't have to perform that heavy calculation with every renderer. As with useCallback you have to be careful when implementing these 2 hooks. If you can't measure the optimization, memoization is actually not worth it.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Before you start optimizing your React application, you should consider whether it is useful to optimize your application. Otherwise you run the risk of slowing down your application instead of speeding it up