DEV Community

Discussion on: React refs in a loop

Collapse
 
robiiiiiiiiiiiin profile image
Robiiiiiiiiiiiin • Edited

Hi, nice article, it helped me to solve a problem.

But I was wondering why you create an array with useRef([]), then create some refs inside that ref who is an array... doesn't that create a ref in a ref?

Couldn't you just make that instead?

const myRefs = things.map(() => createRef())
Enter fullscreen mode Exit fullscreen mode

Then refer to it like that in the <button>:

ref={myRefs[i]}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nicm42 profile image
Nic

For the first question, I can't remember why I needed to do it that way.

When it comes to refer to them, you have to use .current. So myRefs[i] doesn't work, but myRefs.current[i] will.

Collapse
 
poppkent profile image
AUGUSTIN Popp Razanaparany • Edited

the problem is that the part const myRefs = things.map(() => createRef()) will be called everytime the component re-render, so, that will change the refs