Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 377
Sander Cokart Avatar asked Jun 22 '26 14:06

Sander Cokart


1 Answers

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.)

like image 171
james emanon Avatar answered Jun 25 '26 05:06

james emanon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!