| Hook Dependency Arrays :👈 | 👉:How to Test Custom React Hooks |
Why You Should Not Call Hooks Conditionally |
Why You Should Not Call Hooks Conditionally in React
1. What Are React Hooks?
React Hooks are functions that let functional components use React features such as state, effects, context, references, and memoization.
Common Hooks include:
useState— manages component state.useEffect— synchronizes a component with external systems.useContext— reads a value from React Context.useRef— stores a value that persists between renders without triggering a render when it changes.useMemo— caches the result of a calculation.useCallback— caches a function reference.
React relies on the order of Hook calls to associate each Hook with its state and other internal information. Therefore, you must follow the Rules of Hooks.
2. What Is Conditional Hook Calling?
Calling a Hook conditionally means calling it only when a condition is true or false, rather than calling it consistently at the top level of a component or custom Hook.
Incorrect example:
import { useState } from "react";
function UserProfile({ isLoggedIn }) {
if (isLoggedIn) {
const [name, setName] = useState("Sam");
}
return <p>User Profile</p>;
}
This code violates the Rules of Hooks because useState is called inside a conditional block.
If isLoggedIn changes between renders, React may encounter a different sequence of Hook calls.
3. Why Does React Require Hooks to Be Called in the Same Order?
Consider this component:
import { useState } from "react";
function Example({ showSecond }) {
const [first, setFirst] = useState("First");
if (showSecond) {
const [second, setSecond] = useState("Second");
}
const [third, setThird] = useState("Third");
return <p>Example</p>;
}
When showSecond is true, the component calls its Hooks in this order:
useState("First")useState("Second")useState("Third")
When showSecond is false, the order becomes:
useState("First")useState("Third")
The sequence of Hook calls changes between renders. React can no longer safely associate the Hook calls with the same component state positions.
This can result in errors such as:
Rendered fewer hooks than expected.Rendered more hooks than during the previous render.
React may detect the mismatch and throw an error. The underlying problem is that the component did not call its Hooks in a consistent order.
4. Correct Approach: Call Hooks Unconditionally
Call the Hook at the top level, then use conditions inside the Hook's logic or in the component's rendering.
Incorrect approach:
import { useEffect } from "react";
function UserProfile({ isLoggedIn }) {
if (isLoggedIn) {
useEffect(() => {
console.log("User logged in");
}, []);
}
return <p>User Profile</p>;
}
Correct approach:
import { useEffect } from "react";
function UserProfile({ isLoggedIn }) {
useEffect(() => {
if (isLoggedIn) {
console.log("User logged in");
}
}, [isLoggedIn]);
return <p>User Profile</p>;
}
export default UserProfile;
In the corrected version:
useEffectis called on every render.- The condition is evaluated inside the Effect.
- The Effect runs after the initial mount and when
isLoggedInchanges. - The Effect performs its action only when
isLoggedInis true.
5. Example: Conditionally Updating State
Suppose you want to manage a username only when a user is logged in.
Incorrect example:
function Dashboard({ isLoggedIn }) {
if (isLoggedIn) {
const [username, setUsername] = useState("");
}
return <h1>Dashboard</h1>;
}
Correct example:
import { useState } from "react";
function Dashboard({ isLoggedIn }) {
const [username, setUsername] = useState("");
if (!isLoggedIn) {
return <p>Please log in.</p>;
}
return (
<div>
<h1>Welcome, {username || "User"}</h1>
<input
value={username}
onChange={event => setUsername(event.target.value)}
placeholder="Enter your name"
/>
</div>
);
}
export default Dashboard;
The Hook is always called before the conditional return. This keeps the Hook call order consistent.
Important: You may use conditions to decide what the component renders. The restriction is on calling Hooks conditionally, not on using conditional logic in general.
6. Can You Call Hooks After an Early Return?
No. A Hook must not be skipped because an early return is reached.
Incorrect example:
import { useEffect } from "react";
function UserProfile({ user }) {
if (!user) {
return <p>No user found.</p>;
}
useEffect(() => {
console.log("User:", user.name);
}, [user]);
return <h1>{user.name}</h1>;
}
When user is missing, the component returns before calling useEffect. When user is present, the component calls it. The Hook sequence can therefore change between renders.
Correct example:
import { useEffect } from "react";
function UserProfile({ user }) {
useEffect(() => {
if (user) {
console.log("User:", user.name);
}
}, [user]);
if (!user) {
return <p>No user found.</p>;
}
return <h1>{user.name}</h1>;
}
export default UserProfile;
Here, the Hook is called before the early return on every render.
7. Alternative Approach: Use Separate Components
Sometimes, a Hook is needed only when a particular section of the interface is displayed. In that case, create a separate component and call the Hook at the top level of that component.
Example:
import { useEffect, useState } from "react";
function UserDetails() {
const [user, setUser] = useState(null);
useEffect(() => {
let ignore = false;
async function loadUser() {
const response = await fetch("/api/user");
const data = await response.json();
if (!ignore) {
setUser(data);
}
}
loadUser();
return () => {
ignore = true;
};
}, []);
if (!user) {
return <p>Loading user...</p>;
}
return <h2>{user.name}</h2>;
}
function Dashboard({ showUser }) {
return (
<div>
<h1>Dashboard</h1>
{showUser && <UserDetails />}
</div>
);
}
export default Dashboard;
In this example:
Dashboardconditionally rendersUserDetails.UserDetailscalls its Hooks unconditionally at the top level.- When
showUseris false,UserDetailsis not mounted. - When
showUserbecomes true, React mountsUserDetailsand runs its Effect. - When
UserDetailsunmounts, its Effect cleanup runs.
This is a useful approach when the conditional section has its own state, Effects, or other Hook logic.
The example's cleanup flag prevents the component from updating its state after the request's Effect has been cleaned up. In production, also handle HTTP errors and consider aborting the request with AbortController.
8. Can You Call Hooks Inside Loops?
No. You must not call Hooks inside loops because the number and order of Hook calls can change between renders.
Incorrect example:
function ProductList({ products }) {
const prices = [];
for (const product of products) {
const [price, setPrice] = useState(product.price);
prices.push(price);
}
return <p>Products: {prices.length}</p>;
}
If the number of products changes, the number of useState calls also changes. This violates the Rules of Hooks.
Correct approach: Use a separate component for each product.
import { useState } from "react";
function ProductItem({ product }) {
const [price, setPrice] = useState(product.price);
return (
<div>
<span>{product.name}: {price}</span>
<button onClick={() => setPrice(price + 1)}>
Increase Price
</button>
</div>
);
}
function ProductList({ products }) {
return (
<div>
{products.map(product => (
<ProductItem key={product.id} product={product} />
))}
</div>
);
}
export default ProductList;
Each ProductItem instance has its own state, and its Hook calls remain consistent across renders.
9. Can You Call Hooks Inside Conditions in Custom Hooks?
No. Custom Hooks must follow the same Rules of Hooks as React components.
Incorrect example:
function useUserData(enabled) {
if (enabled) {
useEffect(() => {
console.log("Loading user data");
}, []);
}
}
Correct example:
import { useEffect } from "react";
function useUserData(enabled) {
useEffect(() => {
if (!enabled) {
return;
}
console.log("Loading user data");
}, [enabled]);
}
export default useUserData;
The custom Hook always calls useEffect. The enabled condition determines whether the Effect performs its work.
10. What About Conditions Inside useMemo and useCallback?
You must not call Hooks such as useMemo or useCallback conditionally either.
Incorrect example:
if (isEnabled) {
const result = useMemo(() => calculateTotal(items), [items]);
}
Correct example:
const result = useMemo(() => {
if (!isEnabled) {
return 0;
}
return calculateTotal(items);
}, [isEnabled, items]);
Here, useMemo is called on every render. The calculation uses a condition to determine which value to return.
However, if the calculation is inexpensive, you may not need useMemo at all:
const result = isEnabled ? calculateTotal(items) : 0;
Use memoization when it provides a meaningful benefit rather than adding it automatically.
11. How to Detect Conditional Hook Errors
The eslint-plugin-react-hooks package can help detect violations of the Rules of Hooks.
Its recommended lint rules flag problems such as calling Hooks inside conditions, loops, or nested functions.
For example, the linter can identify code like this:
function Example({ enabled }) {
if (enabled) {
useState(0);
}
return null;
}
Follow the linter's recommendations rather than suppressing warnings without understanding the cause.
12. Rules of Hooks: Quick Reference
| Practice | Allowed? | Explanation |
|---|---|---|
| Call Hooks at the top level of a component | Yes | Keeps Hook calls in a consistent order. |
| Call Hooks inside an if statement | No | The Hook may be skipped on some renders. |
| Call Hooks inside a loop | No | The number or order of calls may change. |
| Call Hooks after an early return | No, if the return can skip them | Some renders may call fewer Hooks. |
| Call Hooks inside a custom Hook at its top level | Yes | Custom Hooks follow the same rules. |
| Use conditions inside an Effect | Yes | The Hook is called consistently; the Effect's work is conditional. |
| Conditionally render a component that uses Hooks | Yes | Each component instance manages its own Hook sequence. |
| Use conditions in JSX | Yes | Conditional rendering does not itself violate the Rules of Hooks. |
13. Interview Questions and Answers
Q1. Why should React Hooks not be called conditionally?
React relies on a consistent order of Hook calls to associate each Hook with its internal state and other data. Conditional calls can change that order between renders and cause errors or incorrect behavior.
Q2. Can Hooks be called inside an if statement?
No. Call Hooks at the top level of a React component or custom Hook, before any conditional returns that could skip them.
Q3. Can a Hook be called inside a loop?
No. The number or order of Hook calls could change when the loop's iteration count changes.
Q4. Can Hooks be called inside a custom Hook?
Yes. Custom Hooks can call other Hooks, provided those calls follow the Rules of Hooks.
Q5. Can we conditionally render a component that uses Hooks?
Yes. You can conditionally render a component using a condition in JSX. That component manages its own Hook calls when it is mounted.
Q6. How can you conditionally execute an Effect?
Call useEffect unconditionally, then put the condition inside its callback. Include the reactive values used by the Effect in its dependency array.
Q7. What is the difference between conditional Hook calls and conditional rendering?
Conditional Hook calls are prohibited because they can change the Hook sequence. Conditional rendering is allowed because it determines which UI elements or components React displays.
14. Final Summary
- Always call Hooks at the top level of React components and custom Hooks.
- Do not call Hooks inside conditions, loops, nested functions, or callbacks.
- Do not place Hooks after an early return that could skip them.
- Put conditions inside Hook logic when you need conditional behavior.
- Use separate components when a conditional section needs its own state or Effects.
- Use the React Hooks lint rules to detect common mistakes.
Remember: You can make the work performed by a Hook conditional, but you must not make the Hook call itself conditional.
| Hook Dependency Arrays :👈 | 👉:How to Test Custom React Hooks |
Comments and Discussion