Skip to content

React lazy state initialization

 Published on 8th May 2022

The simplest way to set the initial state of a React component is to pass a value directly to the useState hook.

const [count, setCount] = useState(0);

For a primitive value this is fine, but if the value is the result of an expensive operation this could be problematic. A component only needs to know the initial state on first render, however setting state in this way means that it will also be initialized on every subsequent re-render.

To avoid recalculating the initial state every time a component renders we can perform a lazy initialization. To do this we need to pass a function to useState which returns the computationally expensive operation.

const expensiveOperation = (data) => {
// do something expensive and return the result
};

const [count, setCount] = useState(() => {
return expensiveOperation(data);
});

This way the initial state is only calculated once, on the components first render, which subsequently avoids a potential performance hit.

It’s important to know that for the most part you won’t need to worry about this, but it is a handy tool to have should the situation arise.