Turn Object Into Array Without Changing Its Identity

Viewed 40

In React, the useRef function returns an object with the argument stored under the key current. Sometimes I'd like to use an array, e.g. to keep a list of references, like

const divsRef = useRef([]);
return Array.from({ length: n }, (_, i) => (
  <div
    ref={function (el) {
      divsRef.current[i] = el;
    }}
  />
));

but typing out current all the time is cumbersome. If I do

const divsRef = useRef();
return Array.from({ length: n }, (_, i) => (
  <div
    ref={function (el) {
      divsRef[i] = el;
    }}
  />
));

instead, then the resulting object isn't iterable. Hence my question, is there an easy way to turn an object into an iterable array, without changing its identity (otherwise the object wouldn't persist between rerenders)? I got it iterable by doing Object.setPrototypeOf(divsRef, Object.getPrototypeOf([])) but then [...divsRef] always returns the empty array.

1 Answers

If you don’t need the actual ref for anything other than to access and use the array at its .current property, then you can use this syntax to avoid the repeated typing of that property name:

const {current: divArray} = useRef([]);
// divArray.push(div);
// etc…

And if you do, then just destructure it on a separate line:

const divsRef = useRef([]);
const {current: divArray} = divsRef;
Related