← Back to React, page 6

react-0110 · Easy fresher

What is lazy initialization of state in useState, and why does useState(expensive()) run the function on every render?

The argument to useState is only used on the first render, but JavaScript still evaluates the expression every time the component runs. So useState(expensive()) calls expensive() on every render and throws the result away after the first. Passing a function, useState(() => expensive()), makes React call it once, on the first render only. Use it for costly work such as reading localStorage or building large structures.

Full answer

useState(initialValue) stores initialValue the first time the component renders. On later renders React ignores the argument and returns the current state. This often leads to the belief that the argument is only evaluated once. It is not. The argument is an ordinary JavaScript expression, evaluated before useState is called, on every render.

So const [items, setItems] = useState(createItems()) calls createItems() on each render. The result is ignored after the first render, but the cost is paid every time: parsing JSON from localStorage, filtering a big array, or creating a large object. With frequent re-renders this becomes slow, and it can also be a source of surprising side effects.

Lazy initialization fixes it. If you pass a function, useState(() => createItems()), React calls it only during the first render and uses the return value as the initial state. The function must be pure and take no arguments. You can also pass the function directly: useState(createItems).

When to use it:

  • Reading from localStorage or sessionStorage for an initial value (guarding against server rendering).
  • Building large data structures or running filters and sorts.
  • Anything that parses, loops or allocates a lot.

When not needed: simple literals such as 0, '', [] or {} are cheap, although a new empty array each render is harmless here because only the first is used.

Same idea elsewhere: useRef(new Expensive()) also creates a new object on every render. The usual pattern is to create the value lazily when ref.current is null. useReducer supports a third init argument for the same purpose. useMemo is for recomputation caching, not for initial state.

Strict Mode calls initializer functions twice in development, as it does with other render code, to check they are pure.

The example counts how many times each form runs.

jsx
import { useState } from 'react';

let calls = 0;
function createItems(label) {
  calls += 1;
  console.log(label + ': createItems call number ' + calls);
  return Array.from({ length: 3 }, (_, i) => 'item ' + (i + 1));
}

function Eager() {
  const [items] = useState(createItems('eager'));
  const [, setTick] = useState(0);
  return <button onClick={() => setTick((t) => t + 1)}>Eager ({items.length})</button>;
}

function Lazy() {
  const [items] = useState(() => createItems('lazy'));
  const [, setTick] = useState(0);
  return <button onClick={() => setTick((t) => t + 1)}>Lazy ({items.length})</button>;
}

export default function App() {
  return (
    <div>
      <Eager />
      <Lazy />
    </div>
  );
}

The check pressed each button once. Each press re-renders its component, and the eager form calls createItems again while the lazy form does not. Output of the run: eager: createItems call number 1 lazy: createItems call number 2 eager: createItems call number 3

Key points

  • The useState argument is evaluated on every render, even though React only uses it on the first.
  • Pass a function (useState(() => expensive())) so React calls it once, on the first render.
  • The initializer must be pure and take no arguments.
  • Use it for storage reads, big data and heavy computation. Plain literals do not need it.
  • useRef and useReducer have similar patterns (lazy creation and the init argument).

Common mistakes

  • Believing the useState argument is only evaluated once.
  • Reading localStorage directly in the argument on every render.
  • Passing a function that has side effects as the initializer.
  • Using useMemo to set initial state instead of lazy initialization.
  • Creating objects with new inside useRef(...) on every render.

Follow-ups

  • How would you read an initial value from localStorage safely with server rendering?
  • Why does Strict Mode call the initializer twice?
  • How does the init argument of useReducer work?

Tips

  • Say "the expression runs every render, React just ignores the result". That sentence is the answer.
  • Give a concrete example such as localStorage.
  • Mention that the initializer must be pure.