useMemo

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-23
Updated:
2019-08-15
Tags:
React libraries JavaScript Performance

https://frontendmasters.com/courses/intermediate-react-v2/usememo/

useMemo

This is for performance optimizations. The next component will re-render every one second.

Now, in React, if a parent component changes, then it will re-render all the child components as well. Because these render methods are very fast.

But in this example, he intentionally added a compute heavy function (fibonacci). After 30 iterations, fibonacci will get really slow. The component is set to re-render every 1 second, and every 1 second it has to re-calculatet the fibonacci number, so the browser in general gets very slow.

   //    ****    Memo.js     ****

import React, { useState, useMemo } from "react";

const fibonacci = n => {
  if (n <= 1) {
    return 1;
  }

  return fibonacci(n - 1) + fibonacci(n - 2);
};

const MemoComponent = () => {
  const [num, setNum] = useState(1);
  const [isGreen, setIsGreen] = useState(true);
   // **** 1. without memoisation.  ↴
   // it would be
   //  const fib = fibonacci(num)
   // **** 2. use useMemo.  ↴
   // use pass it the function, and the dependencies
   // and it will only run the function if the dependencies
   // have changed
  const fib = useMemo(() => fibonacci(num), [num]);

  return (
    <div>
      <h1
        onClick={() => setIsGreen(!isGreen)}
        style={{ color: isGreen ? "limegreen" : "crimson}}
      >
        useMemo Example
      </h1>
      <h2>
        Fibonacci of {num} is {fib}
      </h2>
      <button onClick={() => setNum(num + 1)}>➕</button>
    </div>
  );
};

export default MemoComponent;

memo is like a pure component (classes) but for functions