7. What are React Hooks?

Hooks are special functions that allow functional components to use state and lifecycle features that were previously only available in class components.

Introduced in React 16.8, they simplified how we write logic.

useState → Manages local data
useEffect → Handles side effects (API calls, logs)

8. React Hooks Ecosystem

REACT COMPONENT

[ HOOKS: useState, useEffect, useRef ]

LOGIC CONNECTED → UI UPDATED

Hooks act as the bridge between your component's raw logic and the final User Interface.

9. The Rules of Hooks

Rule 1: Top Level Only - Never call hooks inside loops, conditions, or nested functions.

Rule 2: React Functions Only - Only call hooks from React functional components or custom hooks.

Rule 3: The "use" Prefix - All hooks must start with the word use (e.g., useTimer, useAuth).

// ❌ Wrong
if (user) { useState(...) }

// ✅ Correct
const [data, setData] = useState();

11. Most Common Hooks

HookPurpose
useStateAdding local state to components
useEffectRunning code on mount/update (Side Effects)
useContextAccessing global data without props
useRefDirectly accessing a DOM element
useReducerManaging complex state logic

12. useState Hook Example

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

13. useEffect Hook Example

This hook runs code after the component renders. It is perfect for logging or fetching data from an API.

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component has loaded!");
  }, []); // Empty array means it runs once on mount

  return <h1>Hello React</h1>;
}

14. Hooks vs Class Components

FeatureHooks (Modern)Class Components (Legacy)
Code SizeShort & ReadableLong & Complex
StateuseStatethis.state
LifecycleuseEffectcomponentDidMount, etc.
LogicEasily reusableHard to share logic

17. Practice Tasks

Task 1: Counter App with Increase/Decrease.
Task 2: Toggle text visibility (Show/Hide).
Task 3: Input Field: Real-time "Hello [Name]" display.
Task 4: Click Counter: "You clicked X times".

Challenge: Use useEffect to show an alert message as soon as the page loads!

18. Learning Flow

State → Events → Hooks (Complete)

Next Destination: React Router → API Fetch → Project Deployment

Hooks are the heart of Modern React! 💜