IDK - Memoization & useMemo React Hook
Tags: react, performance, beginners, webdev
Published: 2023-05-15 19:24:32

##IDK - Memoization: React.memo & useMemo


I don't know what Memoization is or how it works with React.

That’s okay let's figure it out together.

###What is memoization in React?

Memoization is a computer science technique that stores the output of a function based on the function’s inputs. This way if the function is called again with the same inputs, it will return the cached (stored) result rather than recomputing the output.

###Does Memoization help with performance?

Yes, because of the way Memoization works, by reducing the resources, as well as, the time needed to execute a function. This is especially useful for functions that are called frequently (or expensive 💰). 

###How can Memoization be used in React?

Inside React, Memoization can be utilized with functional components using the **React.memo()** higher-order components. The **React.memo()** function will return a new component that will ONLY re-render if its props change. 

This is exactly how the performance of a React application could be improved when using Memoization. You can now prevent any unnecessary re-renders to the functional components.

For example, you are creating list that will hold a large list of items inside:

```
export const TaskList = ({tasks})=>{  
return (
     <ul>        
      {tasks.map( (task) => (                    

       <li key={task.id}>     
            {task.title} 
       </li>
      ))}         
    </ul> 
 );
}
```

To provide better optimization, you could apply memoization :

```
export const MemoizedTaskList = React.memo(TaskList);   
```

When you wrap the functional component within **React.memo()**, React will only re-render if the props have changed. So, if nothing is added, updated, or removed from the task list and it remains the same. **React.memo()** will perform a shallow comparison of the previous props and the new props and re-render only if the props have changed. 

###React Hook: useMemo() 

useMemo is a built-in React hook that lets you cache the result of an expensive calculation. Again, assisting with optimizing re-rendering performance in the application by telling React to skip re-rendering or to reuse the cached value if the data hadn't changed
####Syntax:

```
const cacheValue = useMemo( calculatedValue, dependencies )
```

####Parameters:

**calculatedValue** - This is the function that will be used to calculate the value that you want to cache.

**dependencies** - A list of reactive values (state, props, functions, and variables declared directly inside the component body) that are referenced in the **calculatedValue** function.

**Reminder:**

-  useMemo is a Hook, which means it must be called at the top level of the component.
-  If you are using Strict Mode, React will call the calculation function twice (According to [react.dev](https://react.dev), this is developmental behavior to find any accidental impurities and does not affect production) 

 **Example:**

```
import {useMemo} from 'react'; 
function TaskList({tasks, tab, theme}) {
 const visibleTasks = useMemo( () => filterTasks(tasks, tab), [tasks, tab]);     
 //...   
}
```
1) `visibleTasks` the variable for our **cacheValue** 
2) `() => filterTasks(tasks, tab)` is the **calculatedValue** function, in this case the function takes no arguments and will return what you want to calculate
3) `[tasks, tab]` are the **dependencies** (or list of reactive values)

One the initial render, useMemo will return the result of the **calculatedValue** function. After that render, React will compare the **dependencies** with the dependencies passed during the previous render. If none of the **dependencies** have been changed, then useMemo will return the cached value. If the **dependencies** had been changed, then React will re-run the calculation and return the new value.

###Additional resources:
https://react.dev/reference/react/useMemo 

Hopefully, this helps to give a better understanding of what Memoization is and how it works, as well as usage of the useMemo React Hook. 

It's okay to say, " I don't know"

We can figure it out together.