This is a test Tutorial on how to build a personal Blog with Gatsby

There are many articles written about React performance optimizations. In general, if some state update is slow, you need to:

  1. Verify you're running a production build. (Development builds are intentionally slower, in extreme cases even by an order of magnitude.)
  2. Verify that you didn't put the state higher in the tree than necessary. (For example, putting input state in a centralized store might not be the best idea.)
  3. Run React DevTools Profiler to see what gets re-rendered, and wrap the most expensive subtrees with memo(). (And add useMemo() where needed.)

This last step is annoying, especially for components in between, and ideally a compiler would do it for you. In the future, it might.

In this post, I want to share two different techniques. They're surprisingly basic, which is why people rarely realize they improve rendering performance.

These techniques are complementary to what you already know! They don't replace memo or useMemo, but they're often good to try first.

An (Artificially) Slow Component

Here's a component with a severe rendering performance problem:

import { useState } from 'react';

export default function App() {
  let [color, setColor] = useState('red');
  return (
    <div>
      <input value={color} onChange={(e) => setColor(e.target.value)} />
      <p style={{ color }}>Hello, world!</p>
      <ExpensiveTree />
    </div>
  );
}

function ExpensiveTree() {
  let now = performance.now();
  while (performance.now() - now < 100) {
    // Artificial delay -- do nothing for 100ms
  }
  return <p>I am a very slow component tree.</p>;
}