Why can't React Hooks be called inside loops or nested function?

前端 未结 1 401
借酒劲吻你
借酒劲吻你 2020-12-03 14:19

React Hooks documentation says to not call Hooks inside loops, conditions, or nested functions.

I understood that the order of execution was importa

相关标签:
1条回答
  • 2020-12-03 15:04

    The reference states the actual cause,

    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.

    and provides the example that shows why this is important.

    Loops, conditions and nested functions are common places where the order in which hooks are executed may be disturbed. If a developer is sure that a loop, etc. is justified and guarantees the order then there's no problem.

    In fact, a loop would be considered valid custom hook if it was extracted to a function, a linter rule can be disabled where needed (a demo):

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const useInputs = n => [...Array(n)].map((_, i) => useState('name' + i));
    

    The example above won't cause problems but a loop isn't necessarily justified; it can be a single array state:

    const App = () => {
      const [inputs, setInputs] = useState(Array(10).fill(''));
      const setInput = (i, v) => {
        setInputs(Object.assign([...inputs], { [i]: v }));
      };
    
      return inputs.map((v, i) => (
        <div key={i}> 
          <input value={v} onChange={e => setInput(i, e.target.value)} />
        </div>
      ));
    }
    
    0 讨论(0)
提交回复
热议问题