React Hooks revolutionized how we write React components. This guide covers all the essential hooks you need to know.
1. useState - State Management
The most basic hook for managing component state:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
2. useEffect - Side Effects
Handle side effects like data fetching and subscriptions:
useEffect(() => {
// Runs after every render
document.title = `Count: ${count}`;
// Cleanup function (optional)
return () => {
console.log('Cleanup');
};
}, [count]); // Dependency array
Pro Tip
Empty dependency array [] means the effect runs only once on mount!
3. useContext - Global State
Access context values without prop drilling:
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click</button>;
}
4. useRef - Mutable References
Access DOM elements and persist values:
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return <input ref={inputRef} />;
}
5. useMemo & useCallback
Optimize performance with memoization:
// Memoize expensive calculations
const expensiveValue = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
// Memoize callback functions
const handleClick = useCallback(() => {
doSomething(a, b);
}, [a, b]);