Reputation: 91
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
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
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
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
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
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