React Hooks
Functions that let you "hook into" React state and lifecycle features from function components without writing a class.
What are React Hooks?
React Hooks are functions that let you use state and other React features in functional components without writing classes. They fundamentally changed how developers write React applications.
Before Hooks (React 16.8, 2019), you needed class components for state. Hooks make functional components just as powerful while being simpler.
Why They Matter
Before Hooks (Class Component):
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <button onClick={() => this.setState({ count: this.state.count + 1 })}>
{this.state.count}
</button>;
}
}
With Hooks (Functional Component):
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Same functionality, 70% less code, no confusing this keyword.
The Main Hooks
useState: Add state to your component
const [count, setCount] = useState(0);
const [name, setName] = useState('');
useEffect: Handle side effects (data fetching, subscriptions, timers)
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // Runs when count changes
useContext: Access context without nested components
const theme = useContext(ThemeContext);
Custom Hooks: The Real Power
Create reusable logic across components:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
// Use in any component
const { data, loading } = useFetch('/api/user');
Extract component logic into reusable functions. This is the real game-changer.
The Rules
- Only call Hooks at the top level - Never in loops or conditions
- Only call from React functions - Components or custom hooks
These rules ensure Hooks work correctly. ESLint enforces them automatically.
Real-World Impact
Airbnb migrated from classes to Hooks and reported:
- 30-40% less component code
- Improved performance
- Easier onboarding for new developers
- More reusable logic
Common Patterns
Form Handling: Extract form logic into a custom hook Window Size: Track window dimensions across components API Data: Reusable data fetching logic
Hooks are not just a feature - they are the modern way to write React. Once you understand them, you will never want to go back to classes.