22
votes

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!

1
What puzzles me here is why !!? is ! not enough? and what about humble .? - marzelin
Although the question has been answered I wanted to share this amazing blog post on React's useState lazy initialization by Kent C. Dodds, you can refer this as well for better understanding. - Amit Mondal

1 Answers

64
votes

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)
}