Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!