DEV Community

Discussion on: 🚫😩 An array of react refs

Collapse
 
joostkiens profile image
Joost Kiens • Edited

How about using a combination of useRef and createRef?

const refs = useRef(collection.map(() => createRef())

return collection.map((x, i) => <div key={i} ref={refs.current[i]}>{x}</div>
Enter fullscreen mode Exit fullscreen mode

The first rule of hooks states we can't call hooks (useRef) in a loop, but we can call createRef in a loop.

The array of refs (from createRef) will not trigger renders and stay in place between renders because it's safely stored in the .current created by useRef.

Using this way, we don't need to know how many refs we need to create upfront and it's a bit less noise (perhaps at the price of a little less clarity). Any downsides with this?