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.
Hooks act as the bridge between your component's raw logic and the final User Interface.
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();
| Hook | Purpose |
|---|---|
useState | Adding local state to components |
useEffect | Running code on mount/update (Side Effects) |
useContext | Accessing global data without props |
useRef | Directly accessing a DOM element |
useReducer | Managing complex state logic |
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>
);
}
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>;
}
| Feature | Hooks (Modern) | Class Components (Legacy) |
|---|---|---|
| Code Size | Short & Readable | Long & Complex |
| State | useState | this.state |
| Lifecycle | useEffect | componentDidMount, etc. |
| Logic | Easily reusable | Hard to share logic |
Challenge: Use useEffect to show an alert message as soon as the page loads!
State → Events → Hooks (Complete)
↓
Next Destination: React Router → API Fetch → Project Deployment