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>;
}