React Hooks: useMemo

React Hooks: useMemo

1. Problem

In the lifecycle of a component, React re-renders the component when an update is made. When React checks for any changes in a component, it may detect an unintended or unexpected change due to how JavaScript handles equality and shallow comparisons. This change in the React application will cause it to re-render unnecessarily.

{% codesandbox jjxypyk86w %}

If one part re-renders, it re-renders the entire component tree.

2. Memoization

Memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

If we have a function compute 1 + 1, it will return 2. But if it uses memoization, the next time we run 1’s through the function, it won’t add them up; it will just remember the answer is 2 without executing the adding function.

3. Syntax

From the official React documentation, syntax is looking like this;

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

useMemo takes in a function and an array of dependencies.

useMemo hook will run the expensive operation when one of the dependencies has been changed. If no changes has been made it will return stored value.

4. Example

Here is an example of useMemo in action.

const memoizedList = useMemo(() => {
  return => {
    return {
      name: someExpensiveOperation(
}, [userList])

5. Use right hook

In addition to useMemo, there is also useCallback and useEffect which can be used similar situations

The useCallback hook is similar to useMemo, but it returns a memoized function rather than memoized value.

If your dependencies array is not provided, there is no possibility of memoization, and it will compute a new value on every render. So in this reason you can go ahead with useEffect

// useMemo - returns -> memoized value
const memoizedValue = useMemo(() => expensiveFunction(a,b), [a,b])

// useCallback - returns -> memoized function
const memoizedCallback = useCallback(() => {
    doSomething(a, b);
  [a, b]