Hooks in Looped Component

Viewed 54

If I loop over an array to create a list of components each of which uses a hook, does that break the only-use-hooks-at-the-top-level rule?

function Parent(props) {
  const [arr, setArr] = useState([])
  const components = arr.map((item, idx) => <Child key={idx} item={item} />)
  return <>{components}</>
}

function Child(props) {
  const [val, setVal] = useState()
  return (
    <>
    //...
    </>
  )
}
1 Answers

If I loop over an array to create a list of components each of which uses a hook, does that break the only-use-hooks-at-the-top-level rule?

No. The hook useState (from your example) is at the top-level of Child so it does not break the rule.

If you are ever unsure whether you're violating the rule, have the React Hooks ESLint plugin react-hooks/rules-of-hooks rule check this for you. create-react-app should have this included for your text editor or IDE (i.e. VSCode) to highlight lines wherever the rule is violated. But if you're not using create-react-app, here are the instructions to manually include it: https://reactjs.org/docs/hooks-rules.html#eslint-plugin

Related