I'm used to passing functions to useState, so that i don't create unnecessary objects:
useState(() => /* create complex obj */)
I expected that useRef would work the same way, but the below returns a function instead of calling it once to intialize, then returning the prev created object after that.
useRef(() => /* create complex obj */).current
I suppose one could do something like this, but seems a lot less clean.
const myRef = useRef();
useEffect(() => {
myRef.current = /* create complex obj */;
}, []);
Am I missing something or is it really a restriction of useRef?
Update
To clarify, this is the usual way to use useState and useRef:
useState(createSimpleInitialValue());
useRef(createSimpleInitialValue());
For each render, you're spending time creating an initial value that will just be discarded after the first pass. This doesn't matter for simple objects, but in the case complex objects it can sometimes be a problem. useState has a workaround:
useState(() => createComplexObj());
Instead of an object, we pass a function. React will invoke the function on the first render, but will not on subsequent passes, so you only have to build the object once. I hoped useRef would have such a feature, but when you pass a function it just stores the function. The docs don't mention that useRef can take a function, but I was hoping there was still some built in way to do it.