🔧 Error Fixes
· 2 min read

React Hooks Error — How to Fix Invalid Hook Call


Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
Error: Rendered more hooks than during the previous render.

You’re breaking one of React’s rules of hooks. Hooks must be called at the top level of a function component, in the same order every render.

Fix 1: Hook Inside a Condition

// ❌ Hook inside an if statement
function Profile({ user }) {
    if (!user) return null;
    const [name, setName] = useState(user.name);  // 💥
}

// ✅ Move hook before the condition
function Profile({ user }) {
    const [name, setName] = useState(user?.name || '');
    if (!user) return null;
}

Fix 2: Hook Inside a Regular Function

// ❌ Calling a hook outside a component
function getUser() {
    const [user, setUser] = useState(null);  // 💥 Not a component
}

// ✅ Hooks only work in components or custom hooks
function useUser() {  // Custom hook (starts with "use")
    const [user, setUser] = useState(null);
    return user;
}

Fix 3: Hook Inside a Loop

// ❌ Hook inside a loop
function UserList({ users }) {
    return users.map(user => {
        const [selected, setSelected] = useState(false);  // 💥
    });
}

// ✅ Extract to a separate component
function UserItem({ user }) {
    const [selected, setSelected] = useState(false);
    return <div>{user.name}</div>;
}

Fix 4: Duplicate React Versions

# ❌ Two copies of React in node_modules
npm ls react
# If you see multiple versions:

# ✅ Deduplicate
npm dedupe
# Or clean install
rm -rf node_modules package-lock.json
npm install

Fix 5: Hook After Early Return

// ❌ Hook after a return statement
function Profile({ id }) {
    if (!id) return <p>No ID</p>;
    const [data, setData] = useState(null);  // 💥 Not called on every render

    // ✅ Move all hooks before any returns
}

Fix 6: Class Component

// ❌ Hooks don't work in class components
class MyComponent extends React.Component {
    render() {
        const [count, setCount] = useState(0);  // 💥
    }
}

// ✅ Convert to function component
function MyComponent() {
    const [count, setCount] = useState(0);
    return <div>{count}</div>;
}
📘