Mastering React Hooks
Introduction to Hooks
React Hooks revolutionized functional components by enabling state management and lifecycle features. Let's explore core hooks:
import { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = \`Count: \${count}\`; }, [count]); return ( <div> <p>{count}</p> <button onClick={() => setCount(c => c + 1)}> Increment </button> </div> ); }
Custom Hooks
Create reusable logic with custom hooks:
function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const stored = localStorage.getItem(key); return stored ? JSON.parse(stored) : initialValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; }
Best Practices
- Follow Hook rules: Only call hooks at the top level
- Use useCallback/useMemo for optimization
- Prefer smaller, focused hooks `