Can we pass function to initial state? What is difference between passing value and passing function?

JavaScriptVeeam

Lazy State Initialization

Yes, you can pass a function to the initialState argument of React's useState hook. This is known as lazy state initialization.

The key difference lies in when the initial state is computed.

Passing a Value (Direct Initialization)

When you pass a value directly, the expression is evaluated on every single render, even though its result is only used for the initial state on the very first render.

This is fine for simple values, but it can be wasteful if the initial state calculation is computationally expensive.

Example

Let's say someExpensiveComputation() is a costly function. In the code below, it runs every time the component re-renders, which is inefficient.


function someExpensiveComputation() {
console.log("Running expensive calculation...");
// ...imagine some heavy processing here...
return 10;
}


function MyComponent() {
// ⚠️ someExpensiveComputation() is called on EVERY render
const [count, setCount] = useState(someExpensiveComputation());


return (
// ...
);
}

Passing a Function (Lazy Initialization)

By passing a function reference, we ensure the expensive computation runs only when the component first mounts.

function someExpensiveComputation() {
console.log("Running expensive calculation...");
// ...imagine some heavy processing here...
return 10;
}


function MyComponent() {
// ✅ The function is passed, not its result.
// React calls it ONLY ONCE on the initial render.
const [count, setCount] = useState(() => someExpensiveComputation());


return (
// ...
);
}

Notice we are passing an anonymous function () => someExpensiveComputation() which then calls our function. You could also pass the function reference directly if it takes no arguments: useState(someExpensiveComputation).

When to use which?

  • Pass a Value: Use this for simple, primitive initial states that don't require any calculation (e.g., useState(0), useState(''), useState(false)).
  • Pass a Function (Lazy State): Use this when the initial state is computationally expensive. This includes:
    • Reading from localStorage or sessionStorage.
    • Performing complex calculations or looping through a large array.
    • Any operation you only want to run once to set up the component's state.
00:00

Table of Contents