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.
function Profile() {
const [ordersCount, setOrdersCount] = useState(0);
if (ordersCount !== 0) {
useEffect(function() { // Noncompliant: Hook is called conditionally
localStorage.setItem('ordersData', ordersCount);
});
}
return <div>{ getName() }</div>
}
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.
function Profile() {
const [ordersCount, setOrdersCount] = useState(0);
useEffect(function() {
if (ordersCount !== 0) {
localStorage.setItem('ordersData', ordersCount);
}
});
const [name] = useState('John');
return <div>{ name }</div>
}