# Memorization

## [React.memo](https://blog.errorbaker.tw/posts/tian/you-might-not-need-react-memo/)

```javascript

// 只要 props 沒變就不會 re-render
function TableValues(props) {}

export default React.memo(TableValues)
```

* 適用 child component 是 pure 也就是沒有 useStae, useContext 時



## Implement memo

array 是 by reference 所以 map 的 key 不能直接 \[1, 2] ，不然有可能&#x20;

```javascript
// map
{
  [1,2]: 3,
  [1,2]: 3,
  [1,2]: 3
}

// need to convert to like 1_2
{
  "1_2": 3
}
```

```javascript
function memo(func, resolver) {
  // your code here
  let lookup = new Map()
  let result = 0;
  return function (...args) {
      const key = resolver ? resolver(...args) : args.join('_')
      if(!lookup.has(key)){
        lookup.set(key, func(...args))
      }
      console.log(lookup)
      return lookup.get(key)
  }
}
const func = (arg1, arg2) => {
  return arg1 + arg2
}
const memoed = memo(func)

memoed(1, 2) 
memoed(1, 2) 
memoed(1, 3)
```

