useState
in ReactLazy initialization in useState
helps optimize performance by computing the initial state only when the component first renders, rather than on every render.
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.
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>
);
}
useState(() => expensiveCalculation())
ensures expensiveCalculation
only runs once during the initial render.count
is retrieved from React’s state instead of recalculating.0
, ""
, or false
).Approach | Code Example | When to Use? |
---|---|---|
Normal Initialization | useState(0) |
For simple values |
Lazy Initialization | useState(() => expensiveCalculation()) |
When computing the initial state is expensive |