Difference between a = useRef(b); and a = useRef(); a.current = b;

Hi, I've been having a problem with an async callback that I would pass to a component where any state variable called within that callback would always be its initial value instead of the current one. The solution that worked ended up being creating a ref to variables I wanted to use within that callback however if the refs were created like this
const picturesRef = useRef(pictures);
const filesRef = useRef(files);
const picturesRef = useRef(pictures);
const filesRef = useRef(files);
the issue would persist but once I found this other "variant" (?) on SO it did the trick
const picturesRef = useRef<string[]>();
picturesRef.current = pictures;

const filesRef = useRef<File[]>();
filesRef.current = files;
const picturesRef = useRef<string[]>();
picturesRef.current = pictures;

const filesRef = useRef<File[]>();
filesRef.current = files;
Could anyone explain to me how they're different, why the first one didn't work and if there's a better solution so I can better handle that kind of issue in the future
2 Replies
Neto
Neto2y ago
useRef keeps a reference to a element between renders but when you use useRef the component itself was not rendered yet when you use <Component ref={picturesRef} /> you update the ref, making current available
🥐
🥐OP2y ago
that makes so much more sense when you put it like that, thank you
Want results from more Discord servers?
Add your server