Before understanding react lazy state initialization, let's first understand states in React.
Let's take an example. I have a counter app with two states.
count
statedata
state
import React, { useState } from 'react'
const Counter = () => {
const [count, setCount] = useState(1);
const [data, setData] = useState(console.log("expensive operation"));
return (
<div>
<h1>{count}</h1>
<button onClick={() => {
setCount(prevCount => prevCount + 1);
}}>
+
</button>
</div>
)
}
export default Counter
Whenever the app loads, it initializes the count and data states. Now, click the + button to increase the count
, and it will re-render the counter component with the new state values.
Check the console, whenever you click the plus button, the data
state is initialized again and again. This can impact the performance of our app if the operation is time-consuming or expensive.
So, how can we improve this? How can we initialize states that are expensive to set up only once?
This is where the concept of lazy state initialization comes in.
How to implement React lazy state initialization?
React provides a way to initialize the state lazily by passing a function to the useState
hook. This function is called only once when the component is first rendered, and its return value is used as the initial state.
const [count, setCount] = useState(1);
const [data, setData] = useState(() => {
const expensiveData = computeExpensiveData();
return expensiveData();
});
As you can see in the code above, I passed a function to the state instead of a direct value.
How it works?
Without Lazy initialization: If you just pass a value directly to
'useState'
, it would compute that value every time the component re-renders, which could be wasteful if the computation is expensive.const [data, setData] = useState(computeExpensiveData());
With Lazy initialization: By passing a function to
'useState'
, the computation inside the function only occurs once during the initial render.const [data, setData] = useState(() => computeExpensiveData());
When (and When Not) to Use Lazy State Initialization
When to Use:
Use lazy state initialization when the state setup is expensive and should only be done once.
Fetching data from the browser's local storage.
Fetching data from an API or database.
When Not to Use:
Using lazy state initialization for every state may complicate things.
For simple or static initial states, lazy initialization may not offer any significant performance improvement.
Benefits of Lazy State Initialization
Performance Optimization
- As the expensive computation while the initializing state will be done only once when the app renders for the first time, it will increase the performance of the app significantly.
Efficient Resources Usage
- If you need to fetch data from an API or the browser's local storage and set it in the state only when the app loads for the first time, you can use lazy initialization or you can use the
useEffect
hook as well.
- If you need to fetch data from an API or the browser's local storage and set it in the state only when the app loads for the first time, you can use lazy initialization or you can use the
Imporved User Experince:
- It reduces the time needed to load the entire app, providing a better user experience.