Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initial state - What is and how to use it?

Tags:

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!

like image 235
Peter Avatar asked Oct 24 '19 10:10

Peter


People also ask

What is lazy initial state?

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.

What is lazy initialization in Java?

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.

Which React hook uses lazy initialization?

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.

When should I use Layouteffect?

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.


1 Answers

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) } 
like image 92
Dupocas Avatar answered Oct 02 '22 15:10

Dupocas