DEV Community

Armin Bashizade
Armin Bashizade

Posted on

Can you use React Hooks in loops and conditions that guarantee the same order for every render?

React docs say:

Hooks—functions starting with use—can only be called at the top level of your components or your own Hooks. You can’t call Hooks inside conditions, loops, or other nested functions.

and it explains that since hooks have no names that can be used for look-up, their call order is used:

Hooks rely on a stable call order on every render of the same component. This works well in practice because if you follow the rule above (“only call Hooks at the top level”), Hooks will always be called in the same order.

Given that explanation, can you break that rule if you can guarantee the same call order for hooks?

for example here the loop and conditions are applied on a hard-coded object and no input change or side effect will change that, hence the order in which hooks are called remains unchanged (this is just an example to showcase a guaranteed order with loops and conditions, please don't provide alternative solutions for this specific example):

const props = [
  { name: 'p1', initial: 1 },
  { name: 'p2', action: () => {// modify the DOM},
  { name: 'p3', initial: 'str' }
];

const RougeReactComponent = () => {
  const states = [];
  for (const prop of props) {
    if (prop.action) {
      useEffect(prop.action, []);
    }
    else if (prop.initial) {
      states.push(useState(prop.initial));
    }
  }

  return states.map((state, key) => <p key={key}>{state[0]}</p>);
};
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
emmysteven profile image
Emmy Steven

Nice write-up, however, there is room for improvement. A long-form content will be great and a lot better.

Collapse
 
arminbashizade profile image
Armin Bashizade • Edited

sorry, I'm not sure I'm following, I'm asking a question in my post, would you like me to clarify anything?