Hello! Let's dive into the second lesson of our module on custom hooks.
In the previous lesson, we established the "what" and "why" of custom hooks: they are the primary mechanism in React for extracting and reusing stateful logic, leading to cleaner, more maintainable code. We also briefly touched on the fact that for this powerful feature to work, it must adhere to certain rules.
Today, we'll explore those rules in depth. This lesson is crucial because these rules are not mere suggestions; they are fundamental to how hooks are designed and are enforced by React's tooling. Understanding them is essential for writing bug-free components and, especially, for correctly implementing your own custom hooks.
Our goal for this lesson is to learn how to follow the Rules of Hooks when implementing custom logic. By the end, you'll understand not only what the rules are but also why they exist, which will give you a much deeper intuition for how React works under the hood.
The "Why": How Do Hooks Actually Work?
Before I list the rules, let's answer a more fundamental question: How can React know which useState call corresponds to which piece of state between renders? The answer lies in a simple but critical design choice: React relies on a consistent call order of hooks on every render.
To understand this, it's incredibly helpful to see a simplified, reverse-engineered version of the useState hook. Your background in computer science will make this internal mechanism quite intuitive.
How Do React Hooks Actually Work? React.js Deep Dive #3
The video 'How Do React Hooks Actually Work?' provides a brilliant explanation of the internal mechanics of hooks. It builds a simplified version of useState from scratch, revealing why the call order is so important.
Watch from 00:45 to 05:50. The presenter starts with a non-working useState and iteratively fixes it. Focus on the moment they switch from a single state variable to an array of states and introduce an index. This is the key insight.
As you saw, the core idea is that for a given component, React maintains an array (or a similar data structure) to store hook data.
- The first time you call
useState, it stores its data at index0. - The second time you call
useState, it stores its data at index1. - ...and so on.
On the next render, React resets the index to 0 and walks through the hooks again. It expects the first useState call to correspond to the state at index 0, the second to index 1, and so forth.
If you were to wrap a hook call in a condition that is true on one render and false on the next, the call order would change, the indices would get misaligned, and React would try to read the wrong state for the wrong hook. This leads to bugs that can be very difficult to track down.
This brings us to the first, and most important, Rule of Hooks.
The Two Core Rules of Hooks
The React team has codified this dependency on call order into two simple rules. The official React documentation is the best source for these.
The official documentation page 'Rules of Hooks' is the definitive source for this topic. It clearly outlines the two primary rules with straightforward examples of what to do and what not to do.
Please read the sections 'Only call Hooks at the top level' and 'Only call Hooks from React functions'. Pay close attention to the list of places where you should not call hooks.
Let's break these down.
Rule 1: Only Call Hooks at the Top Level
This rule is a direct consequence of the array-based implementation we just discussed. You must always call hooks at the top level of your React function, before any early returns.
This means you cannot call hooks inside:
- Loops (
for,while) - Conditions (
if,else, ternary operators) - Nested functions (including event handlers or functions passed to
useMemo,useEffect, etc.) try/catchblocks
Let's see a common mistake and how to fix it. Imagine you only want to fetch data if an id prop exists.
Incorrect Code (violates Rule 1):
function Product({ id }: { id: string | null }) {
if (!id) {
return <p>No product ID provided.</p>;
}
// 🔴 Bad: Hook is called conditionally
const [product, setProduct] = useState(null);
useEffect(() => {
// fetch product data...
}, [id]);
// ...
}
Correct Code:
function Product({ id }: { id:string | null }) {
// ✅ Good: Hooks are called unconditionally at the top level
const [product, setProduct] = useState(null);
useEffect(() => {
if (id) { // The *logic inside* the hook can be conditional
// fetch product data...
}
}, [id]);
if (!id) {
return <p>No product ID provided.</p>;
}
// ...
}
This short video provides another clear, practical example of this exact issue and a slightly different, but also valid, way to refactor it.
All 12 useState & useEffect Mistakes Junior React Developers Still Make in 2025
The video 'All 12 useState & useEffect Mistakes...' highlights a classic conditional rendering mistake that violates the Rules of Hooks.
Watch the section from 02:32 to 04:44. Notice how moving the conditional return after the hook calls resolves the issue. This reinforces the 'top-level' principle.
Rule 2: Only Call Hooks from React Functions
This rule defines where it's valid to place hook calls.
You can only call hooks from:
- React Function Components: Functions that return JSX and whose names start with a capital letter (e.g.,
function MyComponent() { ... }). - Custom Hooks: Functions whose names start with
use(e.g.,function useMyLogic() { ... }).
This rule is what makes custom hooks possible. The use prefix is a signal to React (and its linter) that this function will contain other hooks and must itself obey the Rules of Hooks. You cannot call hooks from a regular JavaScript utility function or a class component.
Happily, you don't need to commit every detail to memory. The Vite project you set up includes the eslint-plugin-react-hooks package, which will immediately flag any violations of these two rules in your code editor.
Best Practices for Implementing Custom Logic
While the two rules are the only formal requirements, following them when implementing custom hooks requires an awareness of some common patterns and pitfalls.
Avoiding Stale Closures in Effects
One of the most common and subtle bugs you'll encounter when writing useEffect logic (both in components and custom hooks) is the "stale closure". This happens when an effect "closes over" an old value of a state or prop.
A setInterval is the classic way to demonstrate this problem.
All 12 useState & useEffect Mistakes Junior React Developers Still Make in 2025
This clip from the 'Mistakes' video masterfully demonstrates the stale closure problem and two ways to solve it.
Watch from 33:08 to 38:32. Pay close attention to why the first attempt (setCount(count + 1)) fails. Then, understand the final, cleanest solution which uses the 'functional update' form (setCount(prev => prev + 1)).
As the video explained, the useEffect callback was created only once, on the initial render. At that time, count was 0. The closure for the interval function captured this 0 value forever. Every second, it was just calling setCount(0 + 1).
The key takeaways for avoiding this are:
- Use the Functional Update Form: When your new state depends on the previous state, use the functional update form of your state setter (e.g.,
setCount(prevCount => prevCount + 1)). This is the most robust solution as it doesn't require adding dependencies to your effect. React guarantees thatprevCountwill always be the most up-to-date state. - The Exhaustive-Deps Rule: The ESLint plugin also enforces a rule called
react-hooks/exhaustive-deps. It warns you when a variable used inside an effect is not included in its dependency array. Listening to this rule helps prevent stale values because it forces the effect to re-run (and create a new closure) whenever a value it depends on changes.
This is a crucial concept for building custom hooks, as many of them (like useFetch or useDebounce) will rely on useEffect.
Test your understanding!
You are creating a custom hook useDocumentTitle that updates the document's title. Here's a first attempt:
import { useEffect } from 'react';
function useDocumentTitle(title: string) {
useEffect(() => {
document.title = title;
}); // No dependency array
}
Why is this implementation potentially problematic or inefficient, and how would you fix it based on the principles we've discussed?
Show answer
The current implementation is inefficient because the useEffect will run after every single render of the component that uses it, even if the title has not changed. This is because it's missing a dependency array.
The fix is to add title to the dependency array. This tells React to only re-run the effect if the title value has changed since the last render.
Corrected Code:
import { useEffect } from 'react';
function useDocumentTitle(title: string) {
useEffect(() => {
document.title = title;
}, [title]); // ✅ Effect now only runs when the title changes
}
This is a direct application of the exhaustive-deps principle.
Conclusion
The Rules of Hooks are the guardrails that make React's state management system predictable and robust. By understanding the "why" behind them—React's reliance on a stable call order—the rules themselves become intuitive.

Key Takeaways:
- Reason for the Rules: React identifies hooks by their call order during rendering. Changing this order between renders will cause bugs.
- Rule 1: Top Level Only. Never call hooks inside conditions, loops, or nested functions. All hook calls must run in the same order on every render.
- Rule 2: React Functions Only. Only call hooks from function components or other custom hooks (functions starting with
use). - Stale Closures are a Common Pitfall: When using
useEffect, be mindful of values captured from the component scope. Prefer the functional update form (setState(prevState => ...)) to ensure you are always working with the latest state. - Trust the Linter: The
eslint-plugin-react-hooksis your best friend. It will catch violations of these rules for you.
Preview of the Next Lesson:
With these rules firmly in mind, we're ready to build something more powerful. In the next lesson, you will create a generic custom hook with TypeScript. We'll combine everything we've learned to build a reusable, type-safe hook that can be adapted to various data types, showcasing the true power of this pattern.