03 / 04

What is the correct way of passing the initialiser function to useState?

const [todos, setTodos] = useState(createInitialTodos());
  1. 1

    Although the result of createInitialTodos() is only used for the initial render, you’re still calling this function on every render. This can be wasteful if it’s creating large arrays or performing expensive calculations.

const [todos, setTodos] = useState(createInitialTodos);
  1. 1

    If you pass a function to useState, React will only call it during the initialisation phase.

Difficulty: 4/10
Topics: lazy initialization, useState performance, hook syntax

Scenario Questions

0-2 years experience
  1. 1

    You need to initialize a counter state to the result of a heavy calculation. How would you use useState to ensure the calculation runs only once?

  2. 2

    If you write const [value, setValue] = useState(expensiveFn()); what happens on each render, and how would you fix it?

2-5 years experience
  1. 1

    In a feature you added a list component that fetches data and stores it in state using useState. The fetch function is memoized, but you notice the fetch runs on every render. Walk me through why that might be and how you'd change the useState call.

  2. 2

    You refactored a component to use a lazy initializer for state, but the UI sometimes shows stale data after a prop change. Explain the trade‑offs of using a lazy initializer here and how you'd handle updates.

5-8 years experience
  1. 1

    Your team is building a dashboard with many widgets, each initializing large data structures with useState. How would you decide when to use a lazy initializer versus moving the computation outside React, considering performance and memory?

  2. 2

    During a code review you see a component that calls useState(() => computeInitial()) inside a loop that renders multiple instances. What are the implications at scale, and how would you redesign it to avoid unnecessary work?

8+ years experience
  1. 1

    The product is migrating a legacy codebase of class components to functional components. You need to establish a guideline for initializing state that may involve expensive calculations. What policy would you set for using lazy initializers, and how would you enforce it across multiple teams?

  2. 2

    A cross‑team performance incident was traced to many components recomputing heavy defaults on every render. Describe how you would architect a shared utility or pattern to centralize lazy initialization and ensure consistency.

Follow-up Questions

  • What would happen if you omitted the arrow function and just passed the result?
  • Can you think of any scenarios where a lazy initializer might be inappropriate?
  • How does this pattern interact with useEffect that also runs on mount?