CodePark/ questions / React rendering performance
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › React rendering performance

In a production build, Editor renders 5 times while the user types. How many times does "readDraft" print?

function readDraft() {
  console.log("readDraft");
  return JSON.parse(localStorage.getItem("draft") ?? "{}");
}

function Editor() {
  const [draft, setDraft] = useState(readDraft());
  // ...
}
5 times, because readDraft() is called on every render even though React only uses the first result

readDraft() has parentheses, so JavaScript calls it before useState even runs, on every render. React ignores the result after the first render, but the work (reading and parsing localStorage) is already done. The fix is to pass the function itself: useState(readDraft). React then calls it only once.

"Once" is the tempting wrong answer. React does use the value only once, but it can't stop JavaScript from evaluating the argument.
useMemo is the wrong fix, because the lazy initializer is the built-in tool for this.