Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
React hook dynamic name based on loop

I'm using react hooks and I need to dynamically change the hook based on the loop's i value. I feel like there's a simple way to do it but can't find where. Any help is appreciated, thank you.

const [hanzi0, setHanzi0] = useState(0);
const [hanzi1, setHanzi1] = useState(0);
const [hanzi2, setHanzi2] = useState(0);
const [hanzi3, setHanzi3] = useState(0);

for(var i = 0; i < 4; i++) {
        setHanzi0(tmpData[x].hanzi);                    
    }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You cannot dynamically look up a local variable name. It's just not a feature that javascript has.

But what you can do is look up a value in some data structure. Like, say, an array.

const [hanzis, setHanzis] = useState([0,0,0,0])

Now you can update that state like this:

const newHanzis = [...hanzis] // create a shallow copy of the array
for(var i = 0; i < 4; i++) {
    newHanzis[i] = tmpData[i].hanzi
}
setHanzis(newHanzis)

If you need to dynamically access different states, then you don't actually have different states, you have one state that has enough complexity to hold many pieces of data.

about 4 years ago · Juan Pablo Isaza Denunciar

0

for(var i = 0; i < 4; i++) {
  if(i === 0) setHanzi0(tmpData[x].hanzi0);
  if(i === 1) setHanzi1(tmpData[x].hanzi1);
  if(i === 2) setHanzi2(tmpData[x].hanzi2);
  if(i === 3) setHanzi3(tmpData[x].hanzi3);                    
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda