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

132
Views
How to decleare multiple state variables using loop - react state hook

I want to declare some state variable like : processId_1, processId_2, processId_3 ..... processId_n .

const [processId, setProcessId] = useState(0); I just want to use loop on the code to declare these variable. Something like that:

for (let index = 0; index < 30; index++) {
    const [processId["".concat("_",index)], setProcessId]["".concat("_",index)] = useState(0);
    
}

enter image description here

I also want to send them as props. How to do that.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It is possible to create an array of these states. So code would look like this:

const [processIds, setProcessIds] = useState([
    {
      id: '1',
      name: 'processId 1'
    },
    {
      id: '2',
      name: 'processId 2'
    }
]);

const handleClick = () => {
  setProcessIds([...processIds].map(pr => {
        if(pr.id === '1') {
          return {
            ...pr,
            name: 'processId is edited'
          }
        }
        else return pr;
      }))
}

<button onClick={handleClick}>
</button>

UPDATE:

It is possible to add keys into object dynamically like this:

const  obj = {};

for (let i = 10; i <= 20; i++) {
    obj['processId_' + i] = 0;
} 

An example:

const  obj = {};

for (let i = 10; i <= 20; i++) {
    obj['processId_' + i] = 0;
}    

console.log(obj)

about 4 years ago · Santiago Trujillo 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!