Loading...
Loading...
React Hook 'useState' is called conditionally. React Hooks must be called in the exact same order in every component render.React relies on the order of Hook calls to associate state with the correct Hook. If you call Hooks inside conditions, loops, or nested functions, the order can change between renders, breaking React's internal tracking.
Always call all hooks at the top of the component, before any conditions.
// ❌ Hook after early return
function Profile({ userId }) {
if (!userId) return null; // early return
const [user, setUser] = useState(null); // 💥 conditional hook
}
// ✅ Hook before early return
function Profile({ userId }) {
const [user, setUser] = useState(null); // ✅ always called
if (!userId) return null;
return <div>{user?.name}</div>;
}Put the condition inside the useEffect, not around it.
// ❌ Hook inside condition
if (isLoggedIn) {
useEffect(() => { fetchUser(); }, []);
}
// ✅ Condition inside the hook
useEffect(() => {
if (isLoggedIn) fetchUser();
}, [isLoggedIn]);