React Hooks are powerful, but they must follow certain rules to work correctly and avoid bugs.
⚙️ 1. Only Call Hooks at the Top Level
- Don’t call Hooks inside loops, conditions, or nested functions.
- Always call them at the top level of your component or custom hook.
✅ Correct:
function App() {
const [count, setCount] = useState(0);
}
❌ Wrong:
if (show) {
const [count, setCount] = useState(0); // ❌ Not allowed
}
🧩 Why:
React relies on the order of Hook calls between renders to preserve state.
⚙️ 2. Only Call Hooks from React Functions
- Call Hooks only inside:
- Functional components, or
- Custom Hooks (functions starting with
use)
✅ Correct:
function useFetchData() {
const [data, setData] = useState(null);
}
❌ Wrong:
function fetchData() {
const [data, setData] = useState(null); // ❌ Regular function
}
⚙️ 3. Custom Hooks Must Start with "use"
This helps React identify Hooks automatically and apply rules of Hook usage.
✅ Example:
function useUserData() { ... }
⚙️ 4. Dependencies in Hooks
When using useEffect, useMemo, or useCallback, always declare all external dependencies in the dependency array to avoid stale values.
✅ Example:
useEffect(() => {
fetchData(userId);
}, [userId]);
💡 In Short:
🔹 Call hooks only at the top level
🔹 Call hooks only inside React functions
🔹 Prefix custom hooks with “use”
🔹 Include all dependencies in hook arrays