- Hooks should only be called from the top level of a component.
- Never call Hooks from within loops, conditional or nested functions.
Here are some examples of violations of the rule where Hooks are called from within loops, conditional statements, or nested functions:
- Calling a Hook inside a loop:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
for (let i = 0; i < 5; i++) {
// This violates the rule as useState is called inside a loop
useState(i);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default MyComponent;
- Calling a Hook inside a conditional statement:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
if (count === 0) {
// This violates the rule as useState is called inside a conditional statement
useState(count);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default MyComponent;
- Calling a Hook inside a nested function:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
function nestedFunction() {
// This violates the rule as useState is called inside a nested function
useState(count);
}
nestedFunction();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default MyComponent;
In each of these examples, the useState
Hook is being called within a loop, conditional statement, or nested function, which violates the rule that Hooks should only be called from the top level of a component.