Chapter 3 of 4

Strict Mode

What the double invocations are checking, and why not to switch it off.

StrictMode is a development-only wrapper that surfaces unsafe patterns by doing things twice. It renders nothing itself and has no effect in production.

<StrictMode>
  <App />
</StrictMode>

What it does

  • Calls component functions, initialisers, updaters and reducers twice, to expose impure logic.
  • Mounts, cleans up and remounts every component, to expose missing effect cleanup.
  • Warns about deprecated APIs and legacy string refs.

Double rendering finds impurity

// Impure: mutates something outside itself while rendering
let idCounter = 0;
function Row({ item }) {
  idCounter = idCounter + 1;     // doubles under Strict Mode
  return <li id={"row-" + idCounter}>{item.name}</li>;
}

The doubling is the symptom, not the disease. A component that changes external state during render is already unreliable - React may call it more than once for its own reasons, including transitions and re-entrant renders.

Double mounting finds missing cleanup

// Broken: two connections, one leaked
useEffect(() => {
  const connection = connect(roomId);
}, [roomId]);

// Correct: the second mount cleans up the first
useEffect(() => {
  const connection = connect(roomId);
  return () => connection.close();
}, [roomId]);

useInsertionEffect

A rarely used sibling of useEffect that runs before any DOM mutations. It exists for CSS-in-JS libraries that need to inject style rules before layout is calculated.

useInsertionEffect(() => {
  injectStyleRule(".button { color: red }");
}, []);

Decide whether a click was inside a container

Complete isInside so it returns true when the target is the container or a descendant of it.