React.js Performance : useState Lazy Initialization

When you need to set the initial value of the state from a function that returns a value (see below), the function will get called at every re-render even though we only need it during the initial render.

const initialState = caluclateValue(props);
const [someStateVal, setSomeStateValue] = React.useState(initialState);

We can lazy initialize useState with a function like this:

const getInitialState = (props) => caluclateValue(props);
const [someStateVal, setSomeStateValue] = React.useState(initialState);

In this case, React will only call the function when it needs the initial value that is once at the time of first render. This is called “lazy initialization.”

Play with it or test it out here !

blogs