Thinking in React, Slowly

#react#frontend#philosophy

It is easy to build things quickly in React. But it is just as easy to build them badly.

When you first learn React, you are taught that state changes trigger re-renders. You learn to put everything into useState hooks. You learn to make components that fetch their own data.

function Clicker() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

But if you move too fast, you miss the nuance:

  1. Deriving state: You don't need useState for values that can be computed from existing props or state.
  2. Effects are escape hatches: Most of the time, you don't need useEffect to sync data. You can handle it in event handlers.
  3. Component purity: A component should be a pure function of its props.

By slow-cooking your components, you write less code, introduce fewer bugs, and maintain your sanity.