Common Hook Mistakes in React JS – Complete Detailed Notes
React Hooks are special functions that allow functional components to use React features such as state, lifecycle-related synchronization, context, references, and performance optimization. Hooks such as useState, useEffect, useContext, useRef, useMemo, and useCallback make React applications easier to build and maintain. However, using Hooks incorrectly can cause rendering errors, stale values, unnecessary re-renders, memory leaks, and unexpected application behavior.
Understanding common Hook mistakes helps developers write reliable, readable, reusable, and efficient React applications.
1. Learning Objectives
After completing these notes, you will be able to:
- Understand the most common mistakes developers make while using React Hooks.
- Follow the Rules of Hooks correctly.
- Manage state updates without introducing bugs.
- Use
useEffect and dependency arrays properly.
- Prevent stale state, unnecessary effects, and infinite render loops.
- Understand cleanup functions and avoid memory leaks.
- Use
useMemo and useCallback appropriately.
- Debug Hook-related errors and improve React application performance.
2. What Are React Hooks?
React Hooks are functions that let function components use React features without requiring class components. Hooks are called during rendering and must follow specific rules so React can associate each Hook call with the correct component state and behavior.
Commonly used Hooks include:
| Hook |
Purpose |
Common Mistake |
useState |
Stores and updates component state. |
Updating state based on an outdated value. |
useEffect |
Synchronizes a component with external systems. |
Missing dependencies or unnecessary effects. |
useContext |
Reads values from React Context. |
Using a context without the correct provider. |
useRef |
Stores a mutable value or references a DOM element. |
Expecting ref changes to trigger re-renders. |
useMemo |
Caches a calculation result between renders. |
Using memoization unnecessarily. |
useCallback |
Caches a function reference between renders. |
Using it everywhere without a performance reason. |
| Custom Hooks |
Reuse stateful logic across components. |
Calling a custom Hook from an ordinary function or event handler. |
3. Mistake One: Calling Hooks Inside Conditions
One of the most important React Hook rules is that Hooks must not be called inside conditions, loops, or nested functions. React expects Hooks to be called in the same order on every render.
Incorrect Example
import { useState } from 'react';
function UserProfile({ isLoggedIn }) {
if (isLoggedIn) {
const [name, setName] = useState('Guest');
}
return <h2>User Profile</h2>;
}
Why is this incorrect?
- The Hook runs only when
isLoggedIn is true.
- If the condition changes between renders, the order of Hook calls may change.
- This can lead to errors such as “Rendered more hooks than during the previous render.”
Correct Example
import { useState } from 'react';
function UserProfile({ isLoggedIn }) {
const [name, setName] = useState('Guest');
if (!isLoggedIn) {
return <p>Please log in.</p>;
}
return <h2>Welcome, {name}!</h2>;
}
export default UserProfile;
Best practice: Call Hooks at the top level of a function component or custom Hook, before conditional returns. Conditions can be used after the Hooks have been called.
4. Mistake Two: Calling Hooks Inside Loops
Hooks should not be called inside for, while, or other loops. The number of Hook calls could change depending on the loop's iterations.
Incorrect Example
import { useState } from 'react';
function ProductList({ products }) {
const values = [];
for (const product of products) {
const [selected, setSelected] = useState(false);
values.push(selected);
}
return <p>Products: {products.length}</p>;
}
Correct Approach
Move the Hook into a separate component and render that component for each item.
import { useState } from 'react';
function ProductItem({ product }) {
const [selected, setSelected] = useState(false);
return (
<button onClick={() => setSelected(value => !value)}>
{product.name} - {selected ? 'Selected' : 'Not Selected'}
</button>
);
}
function ProductList({ products }) {
return (
<div>
{products.map(product => (
<ProductItem key={product.id} product={product} />
))}
</div>
);
}
export default ProductList;
Key point: Use loops or array methods to render components, but call Hooks inside the components themselves.
5. Mistake Three: Calling Hooks Inside Event Handlers
Event handlers execute in response to user actions, such as button clicks or form submissions. Hooks must not be called inside event handlers because Hooks are intended to run while React renders a function component or custom Hook.
Incorrect Example
function Counter() {
function handleClick() {
const [count, setCount] = useState(0);
setCount(count + 1);
}
return <button onClick={handleClick}>Increase</button>;
}
Correct Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(previousCount => previousCount + 1);
}
return (
<button onClick={handleClick}>
Count: {count}
</button>
);
}
export default Counter;
Explanation: Declare state at the top level. The event handler should update that state using its setter function.
6. Mistake Four: Calling Hooks in Ordinary JavaScript Functions
React Hooks cannot be called from an ordinary JavaScript utility function. They can be called from React function components or custom Hooks.
Incorrect Example
import { useState } from 'react';
function getUserName() {
const [name, setName] = useState('Alex');
return name;
}
Correct Example Using a Component
import { useState } from 'react';
function UserName() {
const [name, setName] = useState('Alex');
return <h2>User: {name}</h2>;
}
export default UserName;
Correct Example Using a Custom Hook
import { useState } from 'react';
function useUserName() {
const [name, setName] = useState('Alex');
return { name, setName };
}
export default useUserName;
A custom Hook conventionally starts with the word use, followed by a descriptive name, such as useUserName or useWindowWidth.
7. Mistake Five: Forgetting the Dependency Array in useEffect
The dependency array determines when an Effect needs to run again. Forgetting the array can cause the Effect to run after every committed render, which may be unnecessary.
Example Without a Dependency Array
import { useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
});
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
This example updates the document title after every committed render. That may be intentional, but it can be wasteful if the Effect does not need to run after every render.
Using Dependencies Correctly
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
Now the Effect runs after the initial commit and again when count changes.
Important: Do not automatically add an empty dependency array to every Effect. Include every reactive value used by the Effect's setup or cleanup logic. The correct dependencies depend on what the Effect actually uses.
8. Mistake Six: Using an Empty Dependency Array Incorrectly
An empty dependency array tells React that the Effect has no reactive dependencies. It does not mean that the Effect should never run again under all circumstances. React runs the Effect after the initial commit, and its cleanup runs when the component is removed. In development Strict Mode, React may also run an extra setup-and-cleanup cycle to help identify cleanup problems.
Potentially Incorrect Example
import { useEffect } from 'react';
function UserGreeting({ username }) {
useEffect(() => {
console.log(`Welcome, ${username}`);
}, []);
return <h2>Hello, {username}</h2>;
}
If the component receives a different username, the Effect will not rerun because the dependency array is empty. The logged value may therefore be outdated.
Correct Example
import { useEffect } from 'react';
function UserGreeting({ username }) {
useEffect(() => {
console.log(`Welcome, ${username}`);
}, [username]);
return <h2>Hello, {username}</h2>;
}
Best practice: Let the dependency array reflect the reactive values used by the Effect. Do not omit dependencies just to prevent an Effect from running again.
9. Mistake Seven: Creating Infinite Render Loops
An infinite render loop can occur when an Effect updates state and that state update causes the Effect to run again repeatedly.
Incorrect Example
import { useEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1);
}, [count]);
return <p>Count: {count}</p>;
}
Why does this happen?
- The component renders with the current count.
- The Effect runs and increases the count.
- The state update triggers another render.
- The dependency changes, so the Effect runs again.
- The cycle continues.
Correct Example: Update State on a Button Click
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(value => value + 1)}>
Count: {count}
</button>
);
}
export default Example;
Best practice: Use Effects to synchronize with external systems, such as timers, subscriptions, or browser APIs. Avoid using an Effect merely to update state that can be calculated during rendering or updated directly in an event handler.
10. Mistake Eight: Updating State Incorrectly
React state behaves as a snapshot for a particular render. Calling a state setter requests another render; it does not change the state variable inside the currently executing code immediately.
Incorrect Example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function incrementTwice() {
setCount(count + 1);
setCount(count + 1);
}
return (
<button onClick={incrementTwice}>
Count: {count}
</button>
);
}
Both updates use the same current-render value of count, so clicking the button increases the count by one rather than two.
Correct Example
function incrementTwice() {
setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);
}
The functional updater receives the latest queued state value. It is especially useful when the next state depends on the previous state.
11. Mistake Nine: Mutating State Directly
State objects and arrays should be treated as immutable. Changing an existing object or array directly can prevent React from recognizing the intended update because the reference may remain unchanged.
Incorrect Example
const [user, setUser] = useState({
name: 'Alex',
age: 25
});
function updateAge() {
user.age = 26;
setUser(user);
}
Correct Example
function updateAge() {
setUser(previousUser => ({
...previousUser,
age: 26
}));
}
Correct Array Update
const [items, setItems] = useState(['Apple', 'Banana']);
function addItem() {
setItems(previousItems => [...previousItems, 'Orange']);
}
Remember: Use object spread, array spread, or suitable immutable update patterns to create a new object or array rather than mutating existing state.
12. Mistake Ten: Forgetting the Cleanup Function in useEffect
Some Effects create resources that must be released when the Effect is no longer needed. Examples include timers, event listeners, subscriptions, and network connections. Failing to clean up can cause duplicated work, stale callbacks, or resource leaks.
Incorrect Example
import { useEffect } from 'react';
function WindowListener() {
useEffect(() => {
window.addEventListener('resize', handleResize);
}, []);
function handleResize() {
console.log('Window resized');
}
return <p>Resize the browser window.</p>;
}
The event listener is never removed when the component is unmounted.
Correct Example
import { useEffect } from 'react';
function WindowListener() {
useEffect(() => {
function handleResize() {
console.log('Window resized');
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <p>Resize the browser window.</p>;
}
export default WindowListener;
The cleanup function removes the listener. React also calls cleanup before rerunning an Effect whose dependencies have changed.
13. Mistake Eleven: Using useEffect for Derived State
Derived state is a value that can be calculated from existing props or state. Storing a derived value separately and synchronizing it with an Effect can add unnecessary renders and make the code harder to maintain.
Unnecessary Approach
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const [total, setTotal] = useState(200);
useEffect(() => {
setTotal(price * quantity);
}, [price, quantity]);
Better Approach
const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const total = price * quantity;
Here, total is calculated during rendering, so there is no need to maintain a separate state variable or Effect.
Best practice: If a value can be calculated directly from current props and state, calculate it during rendering. Consider useMemo only when the calculation is expensive enough to justify memoization.
14. Mistake Twelve: Using useRef When State Is Required
The useRef Hook stores a mutable value that persists between renders. Updating ref.current does not trigger a re-render. Therefore, it is not a replacement for state when the updated value must appear in the UI.
Incorrect Example
import { useRef } from 'react';
function Counter() {
const count = useRef(0);
function increment() {
count.current += 1;
}
return (
<button onClick={increment}>
Count: {count.current}
</button>
);
}
The reference value changes, but React does not re-render the component to display the new value.
Correct Example Using useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(value => value + 1)}>
Count: {count}
</button>
);
}
export default Counter;
Use useState when a value affects the displayed UI. Use useRef for values such as DOM references, timer IDs, or mutable information that does not need to trigger rendering.
15. Mistake Thirteen: Using useMemo and useCallback Everywhere
useMemo caches a calculation result, while useCallback caches a function reference. Both are performance optimization tools, not requirements for every component or function.
Unnecessary Memoization
import { useCallback } from 'react';
function Greeting({ name }) {
const getMessage = useCallback(() => {
return `Hello, ${name}`;
}, [name]);
return <p>{getMessage()}</p>;
}
For a simple string, the extra Hook may not provide a meaningful benefit.
Simpler Approach
function Greeting({ name }) {
const message = `Hello, ${name}`;
return <p>{message}</p>;
}
Use memoization when:
- A calculation is measurably expensive.
- A stable function or value helps an optimized child component avoid unnecessary work.
- A dependency-sensitive API genuinely requires a stable reference.
Do not use memoization as a substitute for fixing incorrect state logic, unnecessary Effects, or poorly structured components.
16. Mistake Fourteen: Using Incorrect Dependencies with Objects and Functions
React compares Effect dependencies using Object.is. Objects, arrays, and functions created during rendering usually receive new references on each render. If such a value is a dependency, an Effect may rerun more often than expected.
Potentially Problematic Example
import { useEffect } from 'react';
function Search({ query }) {
const options = { query, limit: 10 };
useEffect(() => {
console.log(options);
}, [options]);
return <p>Searching for: {query}</p>;
}
The options object is recreated on every render, so its reference changes.
Better Approach
import { useEffect } from 'react';
function Search({ query }) {
useEffect(() => {
const options = { query, limit: 10 };
console.log(options);
}, [query]);
return <p>Searching for: {query}</p>;
}
Creating the object inside the Effect makes query the relevant dependency. Always include the reactive values actually used by the Effect.
17. Mistake Fifteen: Ignoring Stale Closures
A closure is a function that retains access to variables from the scope where it was created. In React, a callback or Effect can continue using values from an earlier render if its logic and dependencies are not handled correctly.
Incorrect Example
import { useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Count: {count}</p>;
}
The interval callback captures the initial value of count. Since the Effect does not rerun, the callback repeatedly attempts to set the count to the same value.
Correct Example
import { useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(previousCount => previousCount + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Count: {count}</p>;
}
export default Counter;
The functional updater uses the latest queued state value, so the interval can safely increment the count without reading a stale count value.
18. Mistake Sixteen: Forgetting That State Updates Are Asynchronous in Practice
Calling a state setter schedules an update; it does not immediately change the state snapshot within the current function execution. Developers sometimes expect the new value to be available on the next line.
Incorrect Expectation
function handleClick() {
setCount(count + 1);
console.log(count);
}
The log displays the value from the current render, not necessarily the newly requested value.
Better Approach
function handleClick() {
setCount(previousCount => previousCount + 1);
}
useEffect(() => {
console.log('Updated count:', count);
}, [count]);
Use the event handler for the update. If you need to react to the committed state change, an Effect may be appropriate when that behavior genuinely requires synchronization after rendering. For ordinary calculations and event logic, an Effect is not always necessary.
19. Mistake Seventeen: Misusing useContext
The useContext Hook reads the nearest matching context value provided above the component in the React tree. If the component is not wrapped by the expected provider, it receives the context's default value.
Example of Context Usage
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemeLabel() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
export default function App() {
return (
<ThemeContext.Provider value="dark">
<ThemeLabel />
</ThemeContext.Provider>
);
}
Common mistakes include:
- Forgetting to wrap the relevant component with the correct provider.
- Using a context value with an unexpected shape.
- Creating a new object provider value on every render when a stable value would help performance.
- Expecting context changes not to trigger updates in consumers that read the context.
20. Mistake Eighteen: Defining a Custom Hook Incorrectly
Custom Hooks help reuse stateful logic. They follow the same Hook rules as built-in Hooks. A custom Hook should usually have a name that begins with use and should be called at the top level of a component or another custom Hook.
Example of a Custom Hook
import { useState } from 'react';
function useToggle(initialValue = false) {
const [enabled, setEnabled] = useState(initialValue);
function toggle() {
setEnabled(previousValue => !previousValue);
}
return { enabled, toggle };
}
export default useToggle;
Using the Custom Hook
import useToggle from './useToggle';
function ToggleButton() {
const { enabled, toggle } = useToggle();
return (
<button onClick={toggle}>
{enabled ? 'Enabled' : 'Disabled'}
</button>
);
}
export default ToggleButton;
Important: Each component that calls a custom Hook gets its own Hook state unless the Hook intentionally uses a shared mechanism such as context or an external store. Calling a custom Hook does not automatically create shared state between components.
21. Mistake Nineteen: Ignoring React Strict Mode Behavior
React Strict Mode helps identify potential problems during development. With Strict Mode enabled, React may call rendering logic an extra time and run an additional setup-and-cleanup cycle for Effects during development.
This behavior is intentional and is not the same as saying that every production Effect runs twice.
Example
import { useEffect } from 'react';
function Example() {
useEffect(() => {
console.log('Effect setup');
return () => {
console.log('Effect cleanup');
};
}, []);
return <p>Check the browser console.</p>;
}
export default Example;
Best practices:
- Make Effects safe to start and stop.
- Clean up timers, listeners, subscriptions, and connections.
- Avoid assuming that an Effect's setup function will run exactly once in development.
- Do not disable Strict Mode simply to hide a bug that needs to be fixed.
22. Mistake Twenty: Not Using the React Hooks ESLint Rules
React provides an ESLint plugin that helps identify violations of the Rules of Hooks and missing or incorrect Effect dependencies. It can catch many common mistakes before the application runs.
Installation
npm install -D eslint eslint-plugin-react-hooks
Configure the plugin according to your project's ESLint setup and the version of the plugin you install. For a current React project, follow the official documentation rather than copying an old configuration blindly.
Benefits of linting:
- Detects Hooks called conditionally or inside loops.
- Warns about missing Effect dependencies.
- Helps maintain consistent Hook usage across components.
- Reduces runtime bugs and improves code readability.
23. Mistake Twenty-One: Using useEffect for User Events
An Effect should generally synchronize React with an external system. If an operation must happen directly because a user clicked a button or submitted a form, the event handler is usually the appropriate place.
Unnecessary Pattern
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
if (submitted) {
console.log('Form submitted');
}
}, [submitted]);
More Direct Pattern
function handleSubmit(event) {
event.preventDefault();
console.log('Form submitted');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
Use an Effect when synchronization with an external system is required. Use an event handler for logic that is specifically triggered by a user action.
24. Mistake Twenty-Two: Forgetting Stable Keys When Rendering Lists
Although list keys are not Hooks themselves, incorrect keys can make stateful components behave unexpectedly when items are inserted, removed, or reordered.
Incorrect Example
{items.map((item, index) => (
<ProductItem key={index} product={item} />
))}
Using an array index as a key can cause React to associate component state with the wrong item when list order changes.
Better Example
{items.map(item => (
<ProductItem key={item.id} product={item} />
))}
Use a stable, unique identifier from the data whenever possible.
25. Common Hook Mistakes: Quick Comparison Table
| Common Mistake |
Possible Result |
Recommended Fix |
| Calling Hooks conditionally |
Hook order errors |
Call Hooks at the top level. |
| Calling Hooks inside loops |
Inconsistent Hook order |
Extract a child component. |
| Calling Hooks in event handlers |
Invalid Hook call |
Declare Hooks at component level. |
| Missing dependencies |
Stale values or incorrect synchronization |
Include all required reactive dependencies. |
| Unnecessary Effect state updates |
Extra renders or infinite loops |
Calculate derived values during rendering. |
| Direct state mutation |
Unexpected UI updates |
Create new objects or arrays. |
| Missing cleanup |
Duplicated listeners or resource leaks |
Return a cleanup function when needed. |
| Incorrect state updater |
Lost updates |
Use a functional updater when state depends on previous state. |
| Using ref for displayed state |
UI does not update automatically |
Use useState for displayed values. |
| Unnecessary memoization |
More complexity without meaningful benefit |
Optimize based on actual needs. |
| Incorrect context provider |
Unexpected context value |
Verify provider placement and value. |
| Ignoring Strict Mode |
Cleanup-related development bugs |
Make Effects resilient to setup and cleanup. |
26. Practical Example: A Counter Using Hooks Correctly
The following component demonstrates correct state updates, a simple Effect, and cleanup for a timer. It avoids conditional Hook calls and uses a functional state updater.
import { useEffect, useState } from 'react';
function CounterApp() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Counter: ${count}`;
}, [count]);
return (
<div>
<h2>React Counter</h2>
<p>Current Count: {count}</p>
<button onClick={() => setCount(value => value + 1)}>
Increase
</button>
<button onClick={() => setCount(value => value - 1)}>
Decrease
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}
export default CounterApp;
Why Is This Example Correct?
- Hooks are called at the top level of the component.
- The state setter uses a functional updater for incrementing and decrementing.
- The document title Effect declares
count as a dependency.
- The UI is derived directly from the current state.
- No unnecessary state variable is used for a calculated value.
27. Practical Exercise: Build a React Task Manager
Create a small task manager application that allows users to add tasks, mark tasks as completed, and remove tasks. Apply the correct Hook practices covered in these notes.
Requirements
- Use
useState to store the task list.
- Use a controlled input for the task name.
- Add a task through a form submission handler.
- Use immutable updates when adding, completing, or removing tasks.
- Assign each task a stable, unique ID.
- Do not call Hooks inside event handlers or loops.
- Do not use
useEffect for values that can be calculated from the task list.
- Display the total number of tasks and completed tasks.
Sample Solution
import { useState } from 'react';
function TaskManager() {
const [taskName, setTaskName] = useState('');
const [tasks, setTasks] = useState([]);
function handleSubmit(event) {
event.preventDefault();
const trimmedName = taskName.trim();
if (!trimmedName) return;
const newTask = {
id: crypto.randomUUID(),
name: trimmedName,
completed: false
};
setTasks(previousTasks => [...previousTasks, newTask]);
setTaskName('');
}
function toggleTask(id) {
setTasks(previousTasks =>
previousTasks.map(task =>
task.id === id
? { ...task, completed: !task.completed }
: task
)
);
}
function removeTask(id) {
setTasks(previousTasks =>
previousTasks.filter(task => task.id !== id)
);
}
const completedCount = tasks.filter(task => task.completed).length;
return (
<section>
<h2>Task Manager</h2>
<form onSubmit={handleSubmit}>
<input
value={taskName}
onChange={event => setTaskName(event.target.value)}
placeholder="Enter a task"
/>
<button type="submit">Add Task</button>
</form>
<p>Total: {tasks.length} | Completed: {completedCount}</p>
<ul>
{tasks.map(task => (
<li key={task.id}>
<label>
<input
type="checkbox"
checked={task.completed}
onChange={() => toggleTask(task.id)}
/>
{task.name}
</label>
<button onClick={() => removeTask(task.id)}>
Remove
</button>
</li>
))}
</ul>
</section>
);
}
export default TaskManager;
Note: This example uses crypto.randomUUID(), which is available in modern environments. If your environment does not support it, use another reliable unique-ID approach.
28. Interview Questions and Answers
Q1. What are React Hooks?
React Hooks are functions that let function components use React features such as state, context, references, and Effects.
Q2. What are the Rules of Hooks?
Call Hooks at the top level of function components or custom Hooks. Do not call them conditionally, inside loops, or inside event handlers.
Q3. Why should Hooks not be called inside conditions?
React relies on a consistent Hook call order across renders. Conditional calls can change that order and cause errors or incorrect behavior.
Q4. What is the purpose of the dependency array in useEffect?
It specifies the reactive values that determine when an Effect must be synchronized again. Every reactive value used by the Effect should be included.
Q5. What causes an infinite render loop?
A common cause is an Effect that updates state and then reruns because a dependency changes on every cycle.
Q6. Why should state not be mutated directly?
Direct mutation changes existing data rather than creating a new state value. This can prevent React from recognizing the intended update and makes state behavior harder to reason about.
Q7. What is a stale closure?
A stale closure occurs when a callback or Effect uses values captured from an earlier render when newer values are expected.
Q8. What is the difference between useState and useRef?
useState stores data that can trigger a re-render when updated. useRef stores a mutable value that persists between renders without triggering a re-render when changed.
Q9. Why is cleanup important in useEffect?
Cleanup releases resources such as event listeners, timers, subscriptions, and connections when an Effect is replaced or the component is removed.
Q10. Should useMemo and useCallback be used everywhere?
No. They are optimization tools. Use them when caching a calculation or keeping a stable reference provides a meaningful benefit.
Q11. What is Strict Mode?
Strict Mode is a development tool that helps reveal unsafe patterns and missing Effect cleanup. Some rendering and Effect setup behavior may be repeated during development.
Q12. How can common Hook mistakes be detected?
Use the React Hooks ESLint rules, inspect browser console warnings, test component behavior, and follow the official React documentation.
29. Best Practices for Using React Hooks
- Always follow the Rules of Hooks.
- Use descriptive state and custom Hook names.
- Keep state updates immutable.
- Use functional state updaters when the next value depends on the previous value.
- Include all required reactive values in Effect dependency arrays.
- Do not suppress dependency warnings just to stop an Effect from rerunning.
- Use Effects for external synchronization rather than routine calculations.
- Clean up timers, listeners, and subscriptions when necessary.
- Use refs for mutable values that do not need to trigger rendering.
- Use memoization when it offers a real performance benefit.
- Use stable keys for rendered lists of stateful components.
- Enable and follow the React Hooks ESLint rules.
- Test components under Strict Mode during development.
30. Quick Revision Checklist
- ☑ Hooks are called at the top level.
- ☑ Hooks are not called inside conditions, loops, or event handlers.
- ☑ Hooks are used only in function components or custom Hooks.
- ☑ State is updated using setter functions.
- ☑ Objects and arrays are updated immutably.
- ☑ Functional state updaters are used when appropriate.
- ☑ Effect dependencies include all required reactive values.
- ☑ Effects do not accidentally create infinite render loops.
- ☑ Cleanup functions release external resources.
- ☑ Derived values are calculated without unnecessary Effects.
- ☑ Refs are not used as a replacement for visible state.
- ☑ Memoization is applied only when useful.
- ☑ Context providers and values are configured correctly.
- ☑ ESLint rules are used to catch Hook mistakes.
31. Official React Documentation
32. React JS Training and Course Demo
To strengthen your practical React JS skills, explore the React JS training course and review the course details. You can also register for a course demo to learn more about the training.
33. Conclusion
Understanding common Hook mistakes is essential for writing reliable React applications. The most important practices are to call Hooks consistently at the top level, manage state immutably, specify Effect dependencies correctly, prevent infinite loops, and clean up external resources. Developers should also avoid unnecessary Effects and memoization, choose between state and refs based on whether the UI must update, and use linting tools to catch mistakes early.
With regular practice and a clear understanding of these rules, React developers can create components that are easier to debug, maintain, test, and scale.