Javascript/React: how to create dynamic variable names for a hook in a loop? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript/React: how to create dynamic variable names for a hook in a loop? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to use useAnimation() hook to animate a bunch of divs, like

const anim0 = useAnimation()
const anim1 = useAnimation()
const anim2 = useAnimation()
const anim3 = useAnimation()
...

Is there an easier way creating this in a loop?

Answer

Use an array instead:

const animations = Array.from(
  { length: 4 },
  useAnimation
);

and then reference, eg, animations[0] instead of anim0.

We are here to answer your question about Javascript/React: how to create dynamic variable names for a hook in a loop? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji