Lazy Initialization in useState: What It Is and How to Use It
useState means passing a function to set the initial state so React runs it only once during the first render. This avoids running expensive calculations on every render, improving performance.How It Works
Lazy initialization in useState works by letting you provide a function instead of a direct value when setting the initial state. React calls this function only once, during the very first render, to get the initial state value.
Think of it like ordering a custom cake: instead of baking the cake every time someone asks (which wastes time), you bake it once when the order is placed. Similarly, React runs the function once to prepare the initial state and then remembers it for future renders.
This is helpful when the initial state requires a heavy calculation or fetching data that you don't want to repeat every time the component updates.
Example
This example shows lazy initialization by passing a function to useState. The function runs only once to set the initial count.
import React, { useState } from 'react'; function ExpensiveCounter() { const [count, setCount] = useState(() => { console.log('Calculating initial count...'); // Simulate expensive calculation let initial = 0; for (let i = 0; i < 100000000; i++) { initial += 1; } return initial; }); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default ExpensiveCounter;
When to Use
Use lazy initialization when your initial state needs a costly calculation or setup that you want to avoid repeating on every render. This can include:
- Calculations with loops or complex logic
- Parsing large data or JSON
- Reading from local storage or other synchronous data sources
It helps keep your app fast and responsive by doing the heavy work only once, right when the component first appears.
Key Points
- Lazy initialization uses a function to set initial state in
useState. - The function runs only once during the first render.
- It improves performance by avoiding repeated expensive calculations.
- Ideal for heavy setup or data parsing before state is set.