Lazy initial state – What is and where 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

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

But I am not able to think of any useCase where this lazy initializing of state will be useful!

Like say am my DOM is rendering and it needs the state value, but my useState has not yet initialized it yet!! And say if you have rendered the DOM and the useState ExpensiveComputation has finished will the DOM will re-render !!

Any help would be useful!

Answer

The argument passed to useState is the initialState, the value which initializes your state in the first render and is 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 this 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)
}

Leave a Reply

Your email address will not be published. Required fields are marked *