Chapter 12: Hooks Introduction
Chapter 12 of 15
Chapter 12: Hooks Introduction
12.1 What are Hooks?
Hooks are functions that let you "hook into" React features from function components. They enable state and lifecycle features without classes.
Why Hooks?
- Reuse stateful logic between components
- Simplify complex components
- Easier to understand than classes
- Modern React development approach
Built-in Hooks:
- useState: Manage component state
- useEffect: Handle side effects
- useContext: Access React context
- useReducer: Complex state management
- useMemo: Memoize expensive calculations
- useCallback: Memoize functions
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
12.2 Hook Rules
Hooks must follow specific rules for React to work correctly.
Rule 1: Only Call Hooks at Top Level
- Don't call hooks inside loops, conditions, or nested functions
- Always call hooks in the same order
- Ensures hooks work correctly
// ✅ Correct
function Component() {
const [count, setCount] = useState(0);
useEffect(() => {});
return <div>{count}</div>;
}
// ❌ Wrong
function Component() {
if (condition) {
const [count, setCount] = useState(0); // Don't do this!
}
}
Rule 2: Only Call Hooks from React Functions
- Call hooks from function components
- Call hooks from custom hooks
- Don't call from regular JavaScript functions
12.3 Custom Hooks
Create custom hooks to reuse stateful logic.
// Custom hook
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(c => c + 1);
const decrement = () => setCount(c => c - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
// Use custom hook
function Counter() {
const { count, increment, decrement } = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}
12.4 Hooks Best Practices
Follow best practices when using hooks.
- Follow the rules of hooks
- Create custom hooks for reusable logic
- Use ESLint plugin for hooks
- Keep hooks focused and simple
- Document custom hooks