Skip to main content

Command Palette

Search for a command to run...

React Performance: useState Lazy Initialization

Updated
1 min read
React Performance: useState Lazy Initialization

Whenever 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 the first render. This is called “lazy initialization.”

Play with it or test it out here!

Originally published at https://www.shauryakalia.com.

4 views

More from this blog

K

kaliaverse

17 posts

Shaurya Kalia is a full stack engineer who loves to code, read, travel, dance and train mixed martial arts. He writes about the same and believes in being the jack of all !