Part 15: Introduction to React Hooks & Rules of Hooks
Introduced in React 16.8, Hooks allow you to use state and other React features inside functional components without writing a class.
1. Why Hooks Were Created
- Reusing Stateful Logic: Before hooks, sharing stateful logic required complex patterns like Render Props or Higher-Order Components (HOCs).
- Eliminating Giant Lifecycle Methods: In class components, unrelated logic had to be split across
componentDidMount,componentDidUpdate, andcomponentWillUnmount. - No
thisConfusion: JavaScript'sthiskeyword often led to binding errors in event handlers.
2. The Two Golden Rules of Hooks
React hooks are regular JavaScript functions, but you must adhere to two strict rules:
Rule 1: Only Call Hooks at the Top Level
Do NOT call hooks inside loops, conditions, or nested functions.
// ❌ WRONG: Calling hook inside a condition
function UserProfile({ userId }) {
if (userId) {
useEffect(() => { /* ... */ }); // ILLEGAL!
}
}
// CORRECT: Place condition INSIDE the hook
function UserProfile({ userId }) {
useEffect(() => {
if (userId) {
// Execute side effect
}
}, [userId]);
}
Why?
React relies on the order in which hooks are called during each render to correctly associate state variables with their values. If a condition alters the call order, React loses track of state alignment.
Rule 2: Only Call Hooks from React Functions
Call hooks only from:
1. React functional components.
2. Custom Hooks (functions starting with use).
3. The ESLint Hooks Plugin
Install eslint-plugin-react-hooks to automatically catch rule violations during development:
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
Key Takeaways
- Hooks enable full state and lifecycle management in functional components.
- Always invoke hooks at the top level of your component.
- Never place hooks inside
ifstatements, loops, or nested functions.
In Part 16, we master the most powerful and misunderstood hook: useEffect!

