DEV Community

Discussion on: useState for one-time initializations

Collapse
 
tkdodo profile image
Dominik D

While possible, there is no lazy initializer for useRef. So in this case, the resource constructor will be called on every render and the result will be discarded. This is certainly possible for some cases, but it’s not the same :)

Collapse
 
xr0master profile image
Sergey Khomushin • Edited

I haven't tested it myself, but I have my doubts. From sources:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Thread Thread
 
xr0master profile image
Sergey Khomushin

Tested, you are right. It looks like they talk about the object itself, but do not guarantee that it will be persisted in .current. Well, good to know.