'Lazy initial state - What it is and how to use it?
I am new to react Hooks. Am trying to make use of useState in my code. While I was using it I found a term "Lazy initial state"
https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
But I am not able to think of any use case where this lazy initialising of state will be useful.
Like say my DOM is rendering and it needs the state value, but my useState has not initialised it yet! And say if you have rendered the DOM and the someExpensiveComputation has finished, the DOM will re-render!
Solution 1:[1]
The argument passed to useState is the initialState, the value which initializes your state in the first render and gets disregarded in subsequent renders. But imagine the following situation
const Component = () =>{
const [state, setState] = useState(getInitialHundredItems())
}
Imagine this being called on each render needlessly (remember even though the initial value is disregarded upon next renders, the function which initializes it still gets called).
For use cases like those instead of just provide a value you can pass a function which returns the initial state, this function will only be executed once (initial render) and not on each render like the above code will
const Component = () =>{
const [state, setState] = useState(getInitialHundredItems)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
