In my  previous article I described a few ways to prevent excess re-renders in react applications. I focused on using useMemo and useCallback hooks and memo() HOC. Just a day later an excellent article from Dan Abramov entitled_ Before You memo()_ was published. Today I will present how the techniques presented in his blog may be applied to the problem from my article.

Problem statement

Let’s start with exactly the same code I used in my previous post. I use Fibonacci component to simulate a component that is computationally expensive to render (and so we don’t want to re-render it when not required).

function fib(n) {
  if (n === 0 || n === 1) {
    return 1;
  }

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

export default function Fibonacci({ n }) {
  const result = fib(n);

  return (
    <p className="text-lg">
      fib({n}) = {result}
    </p>
  );
}

And this is how it is used initially. Note that by default every time the text  value changes Fibonacci  component is going to be re-rendered. This ends up being a terrible, sluggish typing experience.

#javascript #react #design-patterns #performance

Improve React Performance without Memo()
1.40 GEEK