Hackforge Academy

Category: react

Call Hooks at the Top Level

Published on 27 Oct 2026

Explanation

Call Hooks at the top level of a React function component or custom Hook. Do not call them inside loops, conditions, or nested functions because React relies on a consistent Hook call order.

Code:

function Profile({ loggedIn }) {
  const [name, setName] = useState('');

  if (!loggedIn) return <p>Please log in</p>;
  return <input value={name} onChange={(e) => setName(e.target.value)} />;
}

Explanation

A Hook called only when a condition is true changes the order of Hook calls between renders. Put the Hook at the top level and place the condition inside the effect or calculation instead.

Code:

function Status({ active }) {
  useEffect(() => {
    if (!active) return;
    console.log('Active');
  }, [active]);

  return <p>{active ? 'Active' : 'Inactive'}</p>;
}

Explanation

React Hooks may be called from function components and custom Hooks, not from ordinary utility functions or class components.

Code:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  // Custom Hook logic goes here.
  return width;
}

function Page() {
  const width = useWindowWidth();
  return <p>Width: {width}</p>;
}

Explanation

React associates Hook state with call order within a component. Keeping the order stable lets React match each state or effect with the correct Hook on every render.

Code:

function Counter() {
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);

  return <button onClick={() => setCount((c) => c + step)}>
    Count: {count}
  </button>;
}

Explanation

The React Hooks ESLint rules can detect many invalid Hook calls and missing effect dependencies. Keep the lint rules enabled to catch bugs before runtime.

Code:

// Good: Hook called at the top level
function Example({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // Load user based on userId.
  }, [userId]);

  return <div>{user?.name}</div>;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community