== Why is this an issue? React relies on the order in which Hooks are called to correctly preserve the state of Hooks between multiple `useState` and `useEffect` calls. This means React Hooks should be called in the same order each time a component renders and should not be called inside loops, conditions, or nested functions. Additionally, this rule ensures that the Hooks are called only from React function components or custom Hooks. [source,javascript,diff-id=1,diff-type=noncompliant] ---- function Profile() { const [ordersCount, setOrdersCount] = useState(0); if (ordersCount !== 0) { useEffect(function() { // Noncompliant: Hook is called conditionally localStorage.setItem('ordersData', ordersCount); }); } return
{ getName() }
} function getName() { const [name] = useState('John'); // Noncompliant: Hook is called from a JavaScript function, not a React component return name; } ---- Instead, always use Hooks at the top of your React function, before any early returns. [source,javascript,diff-id=1,diff-type=compliant] ---- function Profile() { const [ordersCount, setOrdersCount] = useState(0); useEffect(function() { if (ordersCount !== 0) { localStorage.setItem('ordersData', ordersCount); } }); const [name] = useState('John'); return
{ name }
} ---- == Resources === Documentation * https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks[React.dev - Breaking Rules of Hooks] * https://legacy.reactjs.org/docs/hooks-rules.html[React documentation - Rules of Hooks]