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!
It's basically the value that initializes our state on the initial render and is ignored on all subsequent re-renders. Sometimes it is a primitive value like number or boolean, but sometimes it is a result of some expensive computation, maybe getting an item from local storage.
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
So if you pass a function to useState , React will only call the function when it needs the initial value (which is when the component is initially rendered). This is called "lazy initialization." It's a performance optimization.
useLayoutEffect fires synchronously after the DOM mutation and before the browser get to paint the new changes. This hook is especially useful for performing DOM measurement like scroll height, scroll width, scroll position and other style on any DOM element.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With