Part 15: Introduction to React Hooks & Rules of Hooks

Part 15 Technology Updated September 12, 2026

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

  1. Reusing Stateful Logic: Before hooks, sharing stateful logic required complex patterns like Render Props or Higher-Order Components (HOCs).
  2. Eliminating Giant Lifecycle Methods: In class components, unrelated logic had to be split across componentDidMount, componentDidUpdate, and componentWillUnmount.
  3. No this Confusion: JavaScript's this keyword 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 if statements, loops, or nested functions.

In Part 16, we master the most powerful and misunderstood hook: useEffect!