Home > Software engineering >  how to declare hooks inside object?
how to declare hooks inside object?

Time:10-28

I'm using hooks like this

const Ref1 = useRef();
const Ref2 = useRef();
const AllRefs = { Ref1, Ref2 };

is there anyway to write this in shorthand maybe something like this:

const AllRefs = { Ref1:useRef(), Ref2:useRef()};

CodePudding user response:

should it be like this?

import React, { useRef } from "react";

export default function App() {
  const arr = [1, 2, 3];

  const refs = useRef([]);

  return (
    <div className="App">
      {arr.map((item, index) => {
        return (
          <div
            key={index}
            ref={(element) => {
              refs.current[index] = element;
            }}
          >
            {item}
          </div>
        );
      })}
    </div>
  );
}
  • Related