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
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
Share Improve this question asked Dec 19, 2019 at 19:39 Sander CokartSander Cokart 911 gold badge1 silver badge5 bronze badges 4 |5 Answers
Reset to default 6Check 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.)
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.
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.
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
const [uploadAnimal, setAnimal] = useState(['cat']);
const loopFun = () => {
const arr = uploadAnimal
for (let i = 0; i < 10; i++) {
arr.push('DOG')
setUploadCount([...arr])
} };
useState
in a loop is never the solution, but without explaining the goal behind your question, we can't really help more than saying not to do this. – Emile Bergeron Commented Dec 19, 2019 at 19:43