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

The value passed to the useState hook in the initial render is the initial state value, and gets disregarded in subsequent renders. This initial value can be the result of calling a function as in the following situation:

const Component = () => {
  const [state, setState] = useState(getInitialHundredItems())
}

But note that getInitialHundredItems is unconditionally and needlessly called on each render cycle.

For use cases like this instead of just calling a function that returns 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. See Lazy Initial State for details.

const Component = () =>{
  const [state, setState] = useState(getInitialHundredItems)
}

Leave a Comment