Sander Cokart
Sander Cokart

Reputation: 91

create useState in a loop based on array possible?

    const columns = ['task', 'category'];

    for (const text in columns) {
        const [text, setText] = useState();
    }

I wish to create multiple useState things using a loop but to join things together seem to be a problem. What I want it to do is to create consts: task, setTask | category, setCategory

Upvotes: 8

Views: 25122

Answers (5)

Rumesh Madushanka
Rumesh Madushanka

Reputation: 379

const [uploadAnimal, setAnimal] = useState(['cat']);

const loopFun = () => {
const arr = uploadAnimal
for (let i = 0; i < 10; i++) {
  
   arr.push('DOG')
   setUploadCount([...arr])
} };

Upvotes: -1

Fish
Fish

Reputation: 571

const columns = ['task', 'category'];
columns.map( (column, index) => {
  let col = column;
  let setCol = column+index;
  [col, setCol] = useState(false)
})

This way it will give unique state for each iteration of elements in the array columns

Upvotes: 0

Dan Ruswick
Dan Ruswick

Reputation: 3150

Under the hood, useState relies on a linked-list-type nested data structure in the fiber. Each time you call useState that structure is "unwrapped" to get the data associated with the next hook call.

This is a good article that goes into depth about how hooks work.

In theory, so long as your loop always executes the same number of times, you could use a hook inside of the loop. HOWEVER, as other people have said here, this is not a standard way of doing things and is not advisable.

Upvotes: 1

Titus
Titus

Reputation: 22474

const [text, setText] = ... is just a deconstructing assignment, you can store the result of useState(..) (an array with two elements) however you want, for example:

const columns = ['task', 'category'];
const state = {};

for (const prop of columns) {
  const resultArr = useState();
  state[prop] = {
    val: resultArr[0],
    fn: resultArr[1]
  };
}

And you can use the results like this:

<button onClick={() => state.task.fn('new value')}>{state.task.val}</button>

But as @EmileBergeron mentioned, there doesn't seem to be any reason to use useState like this. There is definitely a more conventional way of solving the problem that you're facing.

Upvotes: 3

james emanon
james emanon

Reputation: 11807

Check this out: https://reactjs.org/docs/hooks-rules.html

Explicitly mentions:

Only Call Hooks at the Top Level Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)

Upvotes: 6

Related Questions