Use a lazy initializer with useState

Share this video with your friends

Send Tweet

Something that’s important to recognize is that every time you call the state updater function (like the setName function in our component), that will trigger a re-render of the component that manages that state (the Greeting component in our example). This is exactly what we want to have happen, but it can be a problem in some situations and there are some optimizations we can apply for useState specifically in the event that it is a problem.

In our case, we’re reading into localStorage to initialize our state value for the first render of our Greeting component. But after that first render, we don’t need to read into localStorage anymore because we’re managing that state in memory now (specifically in that name variable that React gives us each render). So reading into localStorage every render after the first one is unnecessary. So React allows us to specify a function instead of an actual value, and then it will only call that function when it needs to–on the initial render.

In this lesson, I’ll show you how to do this and demonstrate how it works.

Márton
Márton
~ 5 years ago

Hi Kent,

From the react docs: "The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded." If it is disregarded, then reading from localstorage happens on the first render only, right? Or only its value is disregarded and localstorage reading is still happening on every render?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 5 years ago

Yes, the value is disregarded, but it's not using the value that's expensive, it's determining the value to pass that's expensive.