Explain the concept of lazy initialization with useState?

Lazy Initialization with useState in React

Lazy initialization in useState helps optimize performance by computing the initial state only when the component first renders, rather than on every render.


1. What is Lazy Initialization?

Normally, useState directly assigns an initial value:

const [count, setCount] = useState(0);

* Issue: If the initial value is expensive to compute (e.g., fetching data, performing calculations), it runs on every render, even if unnecessary.

* Lazy Initialization Fix: Pass a function to useState instead of a value:

const [count, setCount] = useState(() => expensiveCalculation());

Here, expensiveCalculation runs only once, during the initial render.


2. Example: Expensive Calculation with Lazy Initialization
function Counter() {
  function expensiveCalculation() {
    console.log("Running expensive calculation...");
    return 1000; // Imagine a complex operation
  }

  const [count, setCount] = useState(() => expensiveCalculation());

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
    </div>
  );
}
What's Happening?
  • useState(() => expensiveCalculation()) ensures expensiveCalculation only runs once during the initial render.
  • On re-renders, count is retrieved from React’s state instead of recalculating.

3. When Should You Use Lazy Initialization?
* Use it when :
  • The initial state requires expensive computations.
  • The initial state fetches data from local storage, API, or database.
* Don't use it if :
  • The initial value is a simple primitive (like 0, "", or false).
  • The function is lightweight and doesn't impact performance.

Summary :
Approach Code Example When to Use?
Normal Initialization useState(0) For simple values
Lazy Initialization useState(() => expensiveCalculation()) When computing the initial state is expensive