2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-07-07 15:47:35 +02:00
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.
2022-07-22 11:38:13 +02:00
2023-07-07 15:47:35 +02:00
Additionally, this rule ensures that the Hooks are called only from React function components or custom Hooks.
2022-07-22 11:38:13 +02:00
2023-07-07 15:47:35 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2022-07-22 11:38:13 +02:00
----
function Profile() {
const [ordersCount, setOrdersCount] = useState(0);
if (ordersCount !== 0) {
2023-07-07 15:47:35 +02:00
useEffect(function() { // Noncompliant: Hook is called conditionally
2022-07-22 11:38:13 +02:00
localStorage.setItem('ordersData', ordersCount);
});
}
return <div>{ getName() }</div>
}
function getName() {
2023-07-07 15:47:35 +02:00
const [name] = useState('John'); // Noncompliant: Hook is called from a JavaScript function, not a React component
2022-07-22 11:38:13 +02:00
return name;
}
----
2023-07-07 15:47:35 +02:00
Instead, always use Hooks at the top of your React function, before any early returns.
2022-07-22 11:38:13 +02:00
2023-07-07 15:47:35 +02:00
[source,javascript,diff-id=1,diff-type=compliant]
2022-07-22 11:38:13 +02:00
----
function Profile() {
const [ordersCount, setOrdersCount] = useState(0);
useEffect(function() {
if (ordersCount !== 0) {
localStorage.setItem('ordersData', ordersCount);
}
});
const [name] = useState('John');
return <div>{ name }</div>
}
----
2023-05-03 11:06:20 +02:00
== Resources
2022-07-22 11:38:13 +02:00
2023-07-07 15:47:35 +02:00
=== Documentation
2023-10-19 11:46:59 +02:00
* React Documentation - https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks[Breaking Rules of Hooks]
* React Documentation - https://legacy.reactjs.org/docs/hooks-rules.html[Rules of Hooks]