useCallback

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/usecallback/

useCallback

   //   ****   Callback.js   ****

import React, { useState, useEffect, useCallback, memo } from "react";

 // **** 3. uses the memo function.  ↴
 // so this means, that as long as
 // it's provided values don't change,
 // it won't re-render the returned component
 // it also needs the `useCallback` "pair"
 // see step 4.
const ExpensiveComputationComponent = memo(({ compute, count }) => {
  return (
    <div>
      <h1>computed: {compute(count)}</h1>
      <h4>last re-render {new Date().toLocaleTimeString()}</h4>
    </div>
  );
});

const CallbackComponent = () => {
  // time and count are two different states
  const [time, setTime] = useState(new Date());
  const [count, setCount] = useState(1);
  // then useEffect to change the clock
  // normally, React would re-render the whole component
  // every time a state changes
  // but in his demo, the clock re-renders every second
  // but not the 'last re-render' text (see below)
  useEffect(() => {
    const timer = setTimeout(setTime(new Date()), 1000);
    return () => clearTimeout(timer);
  });

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

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

  return (
    <div>
      <h1>useCallback Example {time.toLocaleTimeString()}</h1>
      <button onClick={() => setCount(count + 1)}>
        current count: {count}
      </button>
       // **** 2. the expensive compute part.  ↴
       // this is the one doing the expensive calculation
      <ExpensiveComputationComponent
       // **** 4. use the useCallback.  ↴
       // same as useMemo
       // give it a function and the list of dependencies
        compute={useCallback(fibonacci, [])}
        count={count}
      />
    </div>
  );
};

export default CallbackComponent;

don't overuse useCallback and useMemo!

Only add them, when you start to have a problem. If you add them too early, then you can quickly make a huge mess...