Rules of Hooks in React JS
The Rules of Hooks are guidelines that explain how React Hooks must be used inside React applications. Hooks such as useState, useEffect, useContext, and useRef allow function components to use React features, but they must be called according to specific rules so React can correctly track state and other Hook-related information between renders.
Following these rules helps prevent bugs, unexpected behavior, and incorrect state management in React applications.
Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. Learning Objectives
After completing this topic, you will be able to:
- Understand the meaning and importance of the Rules of Hooks.
- Identify where Hooks can and cannot be called.
- Understand why Hooks must be called at the top level.
- Learn how to use Hooks correctly with conditional logic and loops.
- Understand the difference between React function components, custom Hooks, and ordinary JavaScript functions.
- Recognize common Hook mistakes and fix them.
- Use the React Hooks ESLint rules to help detect incorrect usage.
2. What Are the Rules of Hooks?
The Rules of Hooks are conventions enforced by React and its development tools to ensure Hooks work consistently. React needs to identify each Hook call in the correct order as a component renders.
For most Hooks, there are two fundamental rules:
- Only call Hooks at the top level. Do not call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components or custom Hooks. Do not call them from ordinary JavaScript functions or class components.
These rules apply to Hooks such as useState, useEffect, useContext, and useReducer. React's special use API has different rules for conditional and loop usage, so it should not be confused with ordinary Hooks.
Example of Correct Hook Usage
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
In this example, useState is called at the top level of the Counter function component. The event handler updates the state but does not call a Hook itself.
3. Rule One: Call Hooks Only at the Top Level
Hooks should be called at the top level of a function component or custom Hook. Do not place ordinary Hooks inside conditional statements, loops, or nested functions.
Why Is This Rule Important?
React relies on a consistent order of Hook calls across renders. If a Hook is skipped during one render but called during another, React may associate Hook state with the wrong call, causing errors or unexpected behavior.
Incorrect Example: Hook Inside an If Statement
import { useState } from "react";
function UserProfile({ isLoggedIn }) {
if (isLoggedIn) {
const [name, setName] = useState("Alex");
}
return <h2>User Profile</h2>;
}
Problem: The Hook is called only when isLoggedIn is true. If that value changes between renders, the order of Hook calls can change.
Correct Example
import { useState } from "react";
function UserProfile({ isLoggedIn }) {
const [name, setName] = useState("Alex");
if (!isLoggedIn) {
return <h2>Please log in</h2>;
}
return <h2>Welcome, {name}!</h2>;
}
export default UserProfile;
Explanation: The Hook is called before the conditional return, so it runs in the same order on every render. The condition controls what is displayed, not whether the Hook is called.
Incorrect Example: Hook Inside a Loop
function Example() {
for (let i = 0; i < 3; i++) {
const [value, setValue] = useState(0);
}
return <p>Example</p>;
}
Problem: A Hook is being called repeatedly inside a loop. The number of calls could vary, which breaks the normal Hook calling rules.
Correct Approach
function Example() {
const [firstValue, setFirstValue] = useState(0);
const [secondValue, setSecondValue] = useState(0);
const [thirdValue, setThirdValue] = useState(0);
return <p>Values are managed consistently</p>;
}
When you need to manage a dynamic collection, consider storing the values in an array or object within a single state variable, or creating a separate child component for each item.
Incorrect Example: Hook Inside a Nested Function
function Example() {
function handleClick() {
const [count, setCount] = useState(0);
}
return <button onClick={handleClick}>Click</button>;
}
Problem: The Hook is inside an event handler rather than at the top level of a component or custom Hook.
Correct Example
import { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(previousCount => previousCount + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
export default Example;
Declare Hooks at the top level, then call their returned functions from event handlers when an update is needed.
```html
4. Rule Two: Call Hooks Only from React Functions
Hooks should be called from React function components or custom Hooks. They should not be called from ordinary JavaScript functions because React must manage their execution during component rendering.
Incorrect Example: Hook Inside a Regular Function
import { useState } from "react";
function calculateValue() {
const [value, setValue] = useState(10);
return value;
}
Problem: calculateValue is an ordinary JavaScript function, not a React function component or custom Hook.
Correct Example: Use a Custom Hook
import { useState } from "react";
function useValue() {
const [value, setValue] = useState(10);
return [value, setValue];
}
function ValueDisplay() {
const [value, setValue] = useValue();
return (
<div>
<p>Value: {value}</p>
<button onClick={() => setValue(v => v + 1)}>
Increase Value
</button>
</div>
);
}
export default ValueDisplay;
Explanation: The custom Hook is named useValue and is called at the top level of the ValueDisplay component. The custom Hook can call other Hooks to reuse stateful logic.
Can Hooks Be Used in Class Components?
No. Hooks cannot be called directly inside class components. Class components use class-based state and lifecycle methods. To use Hooks, write a function component or extract reusable logic into a custom Hook used by a function component.
5. Rule Three: Call Hooks Before Conditional Returns
All ordinary Hooks must be called before any conditional return that might skip them. This keeps Hook calls in the same order on every render.
Incorrect Example
import { useState } from "react";
function Profile({ user }) {
if (!user) {
return <p>Loading profile...</p>;
}
const [isFollowing, setIsFollowing] = useState(false);
return <button>{isFollowing ? "Following" : "Follow"}</button>;
}
Problem: When user is missing, the component returns before calling useState. When user becomes available, the Hook is called. This changes the Hook call order between renders.
Correct Example
import { useState } from "react";
function Profile({ user }) {
const [isFollowing, setIsFollowing] = useState(false);
if (!user) {
return <p>Loading profile...</p>;
}
return (
<button onClick={() => setIsFollowing(value => !value)}>
{isFollowing ? "Following" : "Follow"}
</button>
);
}
export default Profile;
Explanation: The Hook is called before the conditional return, so React encounters it in the same order during each render.
6. Rule Four: Do Not Call Hooks Inside Event Handlers
Event handlers execute in response to user actions, such as clicking a button or submitting a form. Ordinary Hooks must not be called inside event handlers. Instead, declare Hooks at the top level and use their returned setter functions inside event handlers.
Incorrect Example
function LoginButton() {
function handleLogin() {
const [loggedIn, setLoggedIn] = useState(false);
}
return <button onClick={handleLogin}>Login</button>;
}
Correct Example
import { useState } from "react";
function LoginButton() {
const [loggedIn, setLoggedIn] = useState(false);
function handleLogin() {
setLoggedIn(true);
}
return (
<button onClick={handleLogin}>
{loggedIn ? "Logged In" : "Login"}
</button>
);
}
export default LoginButton;
Here, useState is called at the top level. The click handler updates the existing state through setLoggedIn.
7. Rule Five: Do Not Call Hooks Inside useEffect, useMemo, or Other Callbacks
Do not call ordinary Hooks inside callback functions passed to other Hooks. Hooks should remain at the top level of the component or custom Hook.
Incorrect Example
import { useMemo, useState } from "react";
function Example() {
const result = useMemo(() => {
const [value, setValue] = useState(0);
return value * 2;
}, []);
return <p>Result: {result}</p>;
}
Problem: useState is called inside the callback passed to useMemo, which violates the Rules of Hooks.
Correct Example
import { useMemo, useState } from "react";
function Example() {
const [value, setValue] = useState(0);
const result = useMemo(() => value * 2, [value]);
return (
<div>
<p>Result: {result}</p>
<button onClick={() => setValue(v => v + 1)}>
Increase
</button>
</div>
);
}
export default Example;
Explanation: Both Hooks are called at the top level. The calculation uses the current value and is recalculated when that dependency changes.
8. Rule Six: Avoid Calling Hooks Inside try/catch/finally Blocks
Ordinary Hooks should not be called inside try, catch, or finally blocks because the execution path may change between renders.
Incorrect Example
function Example() {
try {
const [value, setValue] = useState(0);
} catch (error) {
console.error(error);
}
return <p>Example Component</p>;
}
Correct Example
import { useState } from "react";
function Example() {
const [value, setValue] = useState(0);
function handleAction() {
try {
console.log("Current value:", value);
} catch (error) {
console.error("An error occurred:", error);
}
}
return (
<button onClick={handleAction}>
Check Value
</button>
);
}
export default Example;
Declare Hooks outside the error-handling blocks. Use try/catch for ordinary operations that may throw errors, rather than to control whether a Hook is called.
9. Rule Seven: Follow Hook Dependency Rules
Hooks such as useEffect, useMemo, and useCallback accept dependency arrays. These arrays tell React which reactive values the callback depends on.
Incorrect Example
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, []);
return <button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>;
}
Problem: The effect uses count but the dependency array is empty. The document title will not update when the count changes.
Correct Example
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
export default Counter;
Explanation: The effect reruns when count changes. Follow the Hooks linter's dependency guidance instead of removing dependencies just to silence a warning.
Important: The dependency-array rule is separate from the rule about where Hooks may be called. Both matter for reliable React code.
10. Custom Hooks and the Rules of Hooks
Custom Hooks allow developers to extract reusable stateful logic from components. A custom Hook must start with use followed by a descriptive name, such as useCounter or useWindowSize.
Example: Custom Counter Hook
import { useState } from "react";
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
function increase() {
setCount(value => value + 1);
}
function decrease() {
setCount(value => value - 1);
}
function reset() {
setCount(initialValue);
}
return { count, increase, decrease, reset };
}
function Counter() {
const { count, increase, decrease, reset } = useCounter(5);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Counter;
Explanation: The custom Hook calls useState at its top level and returns reusable state-related functions. The component calls useCounter at its top level.
Each component that calls this custom Hook normally receives its own independent counter state.
11. Special Note: The React use API
React also provides a special API named use. Unlike ordinary Hooks such as useState and useEffect, the use API can be called inside conditions and loops. However, it must still be called from a component or custom Hook, and it must not be wrapped in a try/catch block.
For beginners, focus first on the standard Rules of Hooks for useState, useEffect, and other ordinary Hooks. Do not assume the special behavior of use applies to every Hook.
12. Common Hook Errors and Their Solutions
| Error or Problem |
Possible Cause |
Solution |
| Invalid hook call |
A Hook is called in an unsupported location. |
Call Hooks at the top level of a function component or custom Hook. |
| Rendered fewer hooks than expected |
A Hook is skipped because of a conditional return or condition. |
Move ordinary Hook calls before conditional returns and outside conditions. |
| Rendered more hooks than expected |
A Hook is called conditionally or inside a loop. |
Keep the Hook call order consistent between renders. |
| Effect does not reflect current values |
A required dependency is missing. |
Include the relevant reactive values in the dependency array. |
| Hook is used in a class component |
Hooks are being called inside a class. |
Use class-based APIs or move the logic into a function component. |
| Duplicate React or version mismatch |
The application may resolve incompatible or multiple React copies. |
Check installed React and renderer versions and inspect the dependency tree. |
13. Using ESLint to Check the Rules of Hooks
ESLint is a JavaScript linting tool that can identify coding problems. The official eslint-plugin-react-hooks package checks Hook usage and dependency-related issues.
Installation
npm install eslint-plugin-react-hooks --save-dev
For a modern ESLint flat configuration, the recommended plugin configuration can be added to eslint.config.js:
import reactHooks from "eslint-plugin-react-hooks";
import { defineConfig } from "eslint/config";
export default defineConfig([
reactHooks.configs.flat.recommended
]);
Configuration details depend on the ESLint version and project setup. If the plugin is already configured by your React tooling, avoid adding a duplicate configuration unnecessarily.
Benefits of the Hooks Linter
- Detects Hooks called in conditions, loops, and unsupported functions.
- Identifies missing dependencies in effects and other dependency-aware Hooks.
- Helps catch common mistakes during development.
- Encourages consistent and maintainable React code.
14. Best Practices for Following the Rules of Hooks
- Declare ordinary Hooks at the top level of function components or custom Hooks.
- Never call ordinary Hooks from event handlers.
- Do not place Hooks inside loops, conditions, nested functions, or
try/catch/finally blocks.
- Call Hooks before conditional return statements.
- Use names beginning with
use for custom Hooks.
- Include the required dependencies in
useEffect, useMemo, and useCallback.
- Use state setter functions to update state instead of directly modifying state variables.
- Use the React Hooks ESLint rules to identify mistakes early.
- Keep component logic readable and separate reusable behavior into custom Hooks when appropriate.
- Read the official React documentation when using advanced or newer APIs.
15. Practical Example: Login Status Component
This example demonstrates correct Hook placement, state updates, event handling, and conditional rendering.
Complete Code
import { useState } from "react";
function LoginStatus() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
function handleLogin() {
setIsLoggedIn(true);
}
function handleLogout() {
setIsLoggedIn(false);
}
return (
<div>
<h2>Login Status</h2>
{isLoggedIn ? (
<div>
<p>Welcome! You are logged in.</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<div>
<p>Please log in to continue.</p>
<button onClick={handleLogin}>Login</button>
</div>
)}
</div>
);
}
export default LoginStatus;
How This Example Follows the Rules
useState is called at the top level of the component.
- The login and logout handlers update state but do not call Hooks.
- Conditional rendering controls which message and button appear.
- The Hook is called consistently whether the user is logged in or logged out.
16. Interview Questions and Answers
Q1. What are the Rules of Hooks?
Answer: They are rules that specify where Hooks can be called so React can track Hook state and behavior correctly between renders.
Q2. What are the two main Rules of Hooks?
Answer: Call ordinary Hooks only at the top level, and call them only from React function components or custom Hooks.
Q3. Can useState be called inside an if statement?
Answer: No. Ordinary Hooks such as useState must be called at the top level, outside conditional statements.
Q4. Can Hooks be called inside a button's click handler?
Answer: No. Declare the Hook in the component and use its returned setter or other functions inside the event handler.
Q5. Why should Hooks be called in the same order?
Answer: React relies on a consistent order of ordinary Hook calls to associate state and other Hook data with the correct calls between renders.
Q6. Can custom Hooks call other Hooks?
Answer: Yes. Custom Hooks can call other Hooks as long as they follow the Rules of Hooks.
Q7. Can Hooks be called inside class components?
Answer: No. Hooks are used in function components and custom Hooks, not directly inside class components.
Q8. What is ESLint's role in React Hooks?
Answer: The official React Hooks ESLint plugin detects invalid Hook usage and dependency-related problems.
Q9. Can a Hook be placed after a conditional return?
Answer: Ordinary Hooks should be called before any conditional return that might skip them.
Q10. Is the special React use API subject to exactly the same rules?
Answer: No. React's special use API can be called conditionally or inside loops, but it still has restrictions. These exceptions do not apply to ordinary Hooks such as useState and useEffect.
17. Practice Exercises
- Create a counter component and make sure all Hooks are declared at the top level.
- Build a login component with conditional rendering but no conditional Hook calls.
- Identify and correct a Hook placed inside an event handler.
- Fix a component that calls a Hook after an early return.
- Create a custom Hook named
useToggle to manage a true/false value.
- Use
useEffect to update the document title and add the correct dependencies.
- Configure or inspect the React Hooks ESLint rules in a React project.
- Explain why a Hook inside a loop can cause rendering problems.
18. Quick Revision
- Top-level rule: Call ordinary Hooks at the top level, not inside conditions, loops, or nested functions.
- React-functions rule: Call Hooks from function components or custom Hooks.
- Conditional returns: Call Hooks before early returns that might skip them.
- Event handlers: Update state in handlers; do not call Hooks there.
- Dependency arrays: Include relevant reactive values for effects and memoization Hooks.
- Custom Hooks: Start their names with
use and follow the same rules.
- ESLint: Helps detect invalid Hook calls and missing dependencies.
- Special exception: React's
use API has different rules for conditional and loop usage.
19. Conclusion
The Rules of Hooks are essential for writing reliable React applications. By calling ordinary Hooks at the top level of function components or custom Hooks, maintaining a consistent call order, and following dependency guidance, developers can avoid common rendering and state-management errors.
Practice these rules with small projects before moving on to advanced topics such as custom Hooks, context, effects, and performance optimization.
Learn more through JustAcademy React JS Training or Register for React JS Course Demo.
20. Official Documentation